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?
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.