假设这个字符串:
The fox jumped over the log.
变成:
The fox jumped over the log.
在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?
假设这个字符串:
The fox jumped over the log.
变成:
The fox jumped over the log.
在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?
当前回答
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
or
re.sub("\s\s+", " ", s)
正如用户Martin Thoma在评论中提到的,在PEP 8中,逗号前的空格被列为令人讨厌的地方。
其他回答
string = 'This is a string full of spaces and taps'
string = string.split(' ')
while '' in string:
string.remove('')
string = ' '.join(string)
print(string)
结果:
这是一个充满空格和点击的字符串
def unPretty(S):
# Given a dictionary, JSON, list, float, int, or even a string...
# return a string stripped of CR, LF replaced by space, with multiple spaces reduced to one.
return ' '.join(str(S).replace('\n', ' ').replace('\r', '').split())
一个简单的灵魂
>>> import re
>>> s="The fox jumped over the log."
>>> print re.sub('\s+',' ', s)
The fox jumped over the log.
import re
string = re.sub('[ \t\n]+', ' ', 'The quick brown \n\n \t fox')
这将删除所有的制表符,新行和多个空白与单一空白。
我没有深入研究其他示例,但是我刚刚创建了这个方法来合并多个连续的空格字符。
它不使用任何库,虽然它的脚本长度相对较长,但它不是一个复杂的实现:
def spaceMatcher(command):
"""
Function defined to consolidate multiple whitespace characters in
strings to a single space
"""
# Initiate index to flag if more than one consecutive character
iteration
space_match = 0
space_char = ""
for char in command:
if char == " ":
space_match += 1
space_char += " "
elif (char != " ") & (space_match > 1):
new_command = command.replace(space_char, " ")
space_match = 0
space_char = ""
elif char != " ":
space_match = 0
space_char = ""
return new_command
command = None
command = str(input("Please enter a command ->"))
print(spaceMatcher(command))
print(list(spaceMatcher(command)))