假设这个字符串:
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行)是什么?
当前回答
因为@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
有趣的是,这里几乎空间只有字符串组连接不是那么糟糕 计时显示的中位数总是七次,每次一千次。
其他回答
我没有深入研究其他示例,但是我刚刚创建了这个方法来合并多个连续的空格字符。
它不使用任何库,虽然它的脚本长度相对较长,但它不是一个复杂的实现:
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)))
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())
你也可以在Pandas DataFrame中使用字符串分割技术,而不需要使用.apply(..),如果你需要对大量字符串快速执行操作,这是非常有用的。这是一行话:
df['message'] = (df['message'].str.split()).str.join(' ')
import re
string = re.sub('[ \t\n]+', ' ', 'The quick brown \n\n \t fox')
这将删除所有的制表符,新行和多个空白与单一空白。
>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'