假设这个字符串:
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行)是什么?
当前回答
要去除空白,考虑开头、结尾和单词之间的额外空白,可以使用:
(?<=\s) +|^ +(?=\s)| (?= +[\n\0])
第一个或处理前导空白,第二个或处理字符串开头的前导空白,最后一个处理尾随空白。
为了证明使用,这个链接将为您提供一个测试。
https://regex101.com/r/meBYli/4
这将与re.split函数一起使用。
其他回答
我没有深入研究其他示例,但是我刚刚创建了这个方法来合并多个连续的空格字符。
它不使用任何库,虽然它的脚本长度相对较长,但它不是一个复杂的实现:
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)))
Python开发人员的解决方案:
import re
text1 = 'Python Exercises Are Challenging Exercises'
print("Original string: ", text1)
print("Without extra spaces: ", re.sub(' +', ' ', text1))
输出: 原始字符串:Python练习是具有挑战性的练习 没有额外的空格:Python练习是具有挑战性的练习
这个正是你想要的
old_string = 'The fox jumped over the log '
new_string = " ".join(old_string.split())
print(new_string)
将会导致
The fox jumped over the log.
令人惊讶的是,没有人发布一个简单的函数,它会比所有其他发布的解决方案快得多。是这样的:
def compactSpaces(s):
os = ""
for c in s:
if c != " " or (os and os[-1] != " "):
os += c
return os
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"