Skip to content Skip to sidebar Skip to footer

Replace Multi-spacing In Strings With Single Whitespace - Python

The overhead in looping through the string and replacing double spaces with single ones is taking too much time. Is a faster way of trying to replace multi spacing in strings with

Solution 1:

look at this

In [1]: str1 = "This is    a  foo bar   sentence with  crazy spaces that  irritates   my program "

In [2]: ' '.join(str1.split())
Out[2]: 'This is a foo bar sentence with crazy spaces that irritates my program'

The method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified)

Solution 2:

Using regular expressions:

importrestr1= re.sub(' +', ' ', str1)

' +' matches one or more space characters.

You can also replace all runs of whitespace with

str1 = re.sub('\s+', ' ', str1)

Post a Comment for "Replace Multi-spacing In Strings With Single Whitespace - Python"