在Python中将字符串中的多空格替换为单个空格

3 投票
2 回答
6476 浏览
提问于 2025-04-17 19:27

在处理字符串时,循环遍历字符串,把两个空格替换成一个空格的过程花费的时间太长了。有没有更快的方法可以把多个空格替换成一个空格呢?

我一直是这样做的,但这个方法实在是太慢,太浪费时间了:

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)

2 个回答

5

使用正则表达式

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

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

你还可以把所有连续的空白字符替换成

str1 = re.sub('\s+', ' ', str1)
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() 会把字符串里的所有单词分开,返回一个单词的列表。默认情况下,它会用空格来分隔单词,如果你不指定其他的分隔符的话。

撰写回答