本文介绍了用单个空格替换字符串中的多行距 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
循环遍历字符串和用单个空格替换双空格的开销太长了.尝试用单个空格替换字符串中的多个间距是一种更快的方法吗?
The overhead in looping through the string and replacing double spaces with single ones is taking too much time. Is a faster way of trying to replace multi spacing in strings with a single whitespace?
我一直在这样做,但它太长而且太浪费了:
I've been doing it like this, but it's just way too long and wasteful:
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)
推荐答案
看看这个
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 作为分隔符(如果未指定,则拆分所有空格)
The method split()
returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified)
这篇关于用单个空格替换字符串中的多行距 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!