-1

I have >4000 numbers in a column that need to be manipulated.. They look like this: 040 413 560 89 or 0361 223240

How dow I put it into the folllowing format: +49 (040) 41356089 or +49 (0361) 223240

They all need to have the same country dialling code +49 and then the respective area code put into brackets and some are already in the correct format.

magdmartin
  • 1,712
  • 3
  • 20
  • 43
Mac
  • 1
  • 2
  • 2
    What have you try to do? Please provide some code, we are here to help, not to do it for you – Nuageux May 04 '17 at 14:33
  • What do you mean by *'column'*? What data structure are you dealing with? Show a simplification of your code. I noticed another question you'd asked which is very similar. Be specific. See how to create a [mcve]. What is your precise problem (i.e. what you're unable to do), rather than what is your goal? – Peter Wood May 04 '17 at 19:15
  • Hi Peter. By column I means as in an excel column for example. to be exact Im working on openrefine which accepts GREL or Python for editing the data – Mac May 05 '17 at 11:24

3 Answers3

0

We can split the string into groups:

>>> groups = '040 413 560 89'.split()
>>> groups
['040', '413', '560', '89']

We can slice the groups, and assign to variables, also join the later groups into one string:

>>> city, number = groups[0], ''.join(groups[1:])
>>> city, number
('040', '41356089')

We can format a new string:

>>> '+49 ({}) {}'.format(city, number)
'+49 (040) 41356089'

We can check if a number already starts with +:

>>> '+49 (040) 41356089'.startswith('+')
True
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • hmm thanks. but I have a column with +4000 numbers to need to apply to all of them simultaneously. How can I use .startswith to add +49 to any number that doesnt already have it? – Mac May 04 '17 at 14:49
  • Improve the original question. See [ask], particularly how to create a [mcve]. – Peter Wood May 04 '17 at 15:03
-1

Do so like this:

ls_alreadycorrected = ['(',')','+49']
str_in = '040 413 560 89' #or apply to list

for flag in ls_alreadycorrected:
    if flag not in str_in:
        how_many_spaces = str_in.count(' ')
        if how_many_spaces > 2:
            str_in = str_in.replace(' ','')
            str_out = '+049'+' ' + '(' + str_in[:3] + ') ' + str_in[-8:]
        else:
            str_in = str_in.replace(' ','')
            str_out = '+049'+' ' + '(' + str_in[:4] + ') ' + str_in[-6:]

That's only given you have to types of phone numbers. For a list of numbers, put this on top instead of str_in

for number in list_of_numbers:
    str_in = number

Cheers

dmb
  • 288
  • 2
  • 9
-2

You can do this.

phone  = "456789"
cod = 123

final = str(cod) + phone

Result is "123456789"

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Joseph
  • 97
  • 3
  • 9