Replace multi-spacing in strings with single whitespace - Python

。_饼干妹妹 提交于 2020-06-16 06:19:07

问题


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 a single whitespace?

I've been doing it like this, but it's just way too long and wasteful:

str1 = "This is    a  foo bar   sentence with  crazy spaces that  irritates   my program "

def despace(sentence):
  while "  " in sentence:
    sentence = sentence.replace("  "," ")
  return sentence

print despace(str1)

回答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)




回答2:


Using regular expressions:

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

' +' matches one or more space characters.

You can also replace all runs of whitespace with

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


来源:https://stackoverflow.com/questions/15469665/replace-multi-spacing-in-strings-with-single-whitespace-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!