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

alv*_*vas 2 python string whitespace replace removing-whitespace

循环遍历字符串并用单个空格替换双空格的开销花费了太多时间.尝试用单个空格替换字符串中的多个间距是一种更快的方法吗?

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

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)
Run Code Online (Sandbox Code Playgroud)

ava*_*sal 11

看这个

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'
Run Code Online (Sandbox Code Playgroud)

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


Ada*_*eng 5

使用正则表达式

import re
str1 = re.sub(' +', ' ', str1)
Run Code Online (Sandbox Code Playgroud)

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

您还可以将所有空白运行替换为

str1 = re.sub('\s+', ' ', str1)
Run Code Online (Sandbox Code Playgroud)