Omar Jandali Omar Jandali - 11 months ago 101
Python Question

Adding charaters to a string in specified places - Django

I have a simple python action that I want to take. I have a string. something like

2364968438
. I want to take that string that I have and add a
-
between specific places in the string to make it look like a phone number. something like this
236-496-8438
within my django/python project. I know i am going to have to slice the string into parts but I am having trouble with it.

I want to create a method within the views.py file that will take a string and split it as well as apply the changes..

def numberfy(request, number):
phone =
#code that splits the number and adds hyphen goes here
return phone


Does it matter if it is a string or integer?

Answer Source

Splice it and join it (if your input is already validated):

def dashify(num):
    s = str(num)
    return '-'.join([s[:3], s[3:6], s[6:]])

For example:

>>> dashify(2364968438)
'236-496-8438'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download