假设这个字符串:
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
Text = " You can select below trims for removing white space!! BR Aliakbar "
# trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='')
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='')
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='')
结果:作为代码
"Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar"
"Remove leading space:You can select below trims for removing white space!! BR Aliakbar"
"Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar"
"Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar"
"Remove more than one space: You can select below trims for removing white space!! BR Aliakbar"
其他回答
import re
string = re.sub('[ \t\n]+', ' ', 'The quick brown \n\n \t fox')
这将删除所有的制表符,新行和多个空白与单一空白。
类似于前面的解决方案,但更具体:用一个空格替换两个或多个空格:
>>> import re
>>> s = "The fox jumped over the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'
这样做,并将这样做::)
# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))
要去除空白,考虑开头、结尾和单词之间的额外空白,可以使用:
(?<=\s) +|^ +(?=\s)| (?= +[\n\0])
第一个或处理前导空白,第二个或处理字符串开头的前导空白,最后一个处理尾随空白。
为了证明使用,这个链接将为您提供一个测试。
https://regex101.com/r/meBYli/4
这将与re.split函数一起使用。
" ".join(foo.split())对于所问的问题不太正确,因为它也完全删除了单个前导和/或尾随空格。所以,如果它们也将被1个空白替换,你应该像下面这样做:
" ".join(('*' + foo + '*').split()) [1:-1]
当然,它没有那么优雅。