6
votes

I want to remove all the whitespace between the numbers in a string in python. For example, if I have

my_string = "my phone number is 12 345 6789"

I want it to become

my_string = "my phone number is 123456789"

I thought I could do this for every number:

for i in range(10):
   my_string = my_string.replace(str(i)+" ",str(i))

But this isn't a smart and efficient solution. Any thoughts?

2

2 Answers

18
votes

Just use regex! Now with support for variable number of spaces.

import re
my_string = "my phone number is 12 345 6789"
my_string = re.sub(r'(\d)\s+(\d)', r'\1\2', my_string)
4
votes

Just another regex way, using look-behind/ahead and directly just remove the space instead of also taking out the digits and putting them back in:

>>> re.sub('(?<=\d) (?=\d)', '', my_string)
'my phone number is 123456789'

I like it, but have to admit it's a bit longer and slower:

>>> timeit(lambda: re.sub('(?<=\d) (?=\d)', '', my_string))
1.991465161754789
>>> timeit(lambda: re.sub('(\d) (\d)', '$1$2', my_string))
1.82666541270698