Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces between numbers in a string in python

Tags:

python

string

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?

like image 551
Brian Avatar asked Jul 28 '16 15:07

Brian


People also ask

How do I remove spaces and numbers in a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

How do I remove extra spaces 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.

How do you remove spaces between outputs in Python?

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.


2 Answers

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)
like image 76
Morgan Thrapp Avatar answered Oct 16 '22 06:10

Morgan Thrapp


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
like image 42
Stefan Pochmann Avatar answered Oct 16 '22 07:10

Stefan Pochmann