假设这个字符串:
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函数一起使用。
其他回答
这个正是你想要的
old_string = 'The fox jumped over the log '
new_string = " ".join(old_string.split())
print(new_string)
将会导致
The fox jumped over the log.
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())
我没有深入研究其他示例,但是我刚刚创建了这个方法来合并多个连续的空格字符。
它不使用任何库,虽然它的脚本长度相对较长,但它不是一个复杂的实现:
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)))
一个简单的灵魂
>>> import re
>>> s="The fox jumped over the log."
>>> print re.sub('\s+',' ', s)
The fox jumped over the log.
因为@pythonlarry问这里缺少基于生成器的版本
groupby连接很简单。Groupby将对具有相同键的连续元素进行分组。并返回每个组的键对和元素列表。所以当键是空格空格是返回整个组。
from itertools import groupby
def group_join(string):
return ''.join(' ' if chr==' ' else ''.join(times) for chr,times in groupby(string))
由变体组成的组很简单,但是很慢。现在来看发电机变体。在这里,我们使用了一个迭代器,即字符串,并生成除字符后面的字符外的所有字符。
def generator_join_generator(string):
last=False
for c in string:
if c==' ':
if not last:
last=True
yield ' '
else:
last=False
yield c
def generator_join(string):
return ''.join(generator_join_generator(string))
所以我用其他的方法测量了时间。
while_replace 0.015868543065153062 re_replace 0.22579886706080288 proper_join 0.40058281796518713 group_join 5.53206754301209 generator_join 1.6673167790286243
Hello和World由64KB的空格分隔
while_replace 2.991308711003512 re_replace 0.08232860406860709 proper_join 6.294375243945979 group_join 2.4320066600339487 generator_join 6.329648651066236
不忘原话
while_replace 0.002160938922315836 re_replace 0.008620491018518806 proper_join 0.005650000995956361 group_join 0.028368217987008393 generator_join 0.009435956948436797
有趣的是,这里几乎空间只有字符串组连接不是那么糟糕 计时显示的中位数总是七次,每次一千次。