用单个空格替换字符串中的多间距 - Python [重复]

Posted

技术标签:

【中文标题】用单个空格替换字符串中的多间距 - Python [重复]【英文标题】:Replace multi-spacing in strings with single whitespace - Python [duplicate] 【发布时间】:2013-03-06 08:48:19 【问题描述】:

遍历字符串并用单个空格替换双空格的开销太长了。尝试用单个空格替换字符串中的多个间距是否是一种更快的方法?

我一直在这样做,但它太长而且太浪费了:

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】:

看看这个

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'

split() 方法返回字符串中所有单词的列表,使用 str 作为分隔符(如果未指定,则在所有空格处拆分)

【讨论】:

【参考方案2】:

使用regular expressions:

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

' +' 匹配一个或多个空格字符。

您也可以用

替换所有运行的空白
str1 = re.sub('\s+', ' ', str1)

【讨论】:

以上是关于用单个空格替换字符串中的多间距 - Python [重复]的主要内容,如果未能解决你的问题,请参考以下文章