用单个空格替换字符串中的多个空格- Python

2024-04-23 16:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

循环使用字符串并用单个空格替换双空格的开销太长了。用一个空格替换字符串中的多个空格是一种更快的方法吗?在

我一直是这样做的,但太长太浪费时间了:

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)

Tags: 方法字符串thatfooiswithbarthis
2条回答

看看这个

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作为分隔符(如果未指定,则对所有空白进行拆分)

使用regular expressions

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

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

也可以将所有空格替换为

^{pr2}$

相关问题 更多 >