3

遍历字符串并用单个空格替换双空格的开销花费了太多时间。尝试用单个空格替换字符串中的多个间距的更快方法是什么?

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

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)
4

2 回答 2

15

看这个

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 作为分隔符(如果未指定,则在所有空格上拆分)

于 2013-03-18T04:18:37.350 回答
5

使用正则表达式

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

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

您还可以将所有空格替换为

str1 = re.sub('\s+', ' ', str1)
于 2013-03-18T04:20:44.940 回答