How do i remove spaces between values in python?

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?

asked Jul 28, 2016 at 15:31

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]

answered Jul 28, 2016 at 15:34

Morgan ThrappMorgan Thrapp

9,3563 gold badges45 silver badges62 bronze badges

3

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['[?>> timeit[lambda: re.sub['[?

Chủ Đề