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?
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.
The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With