移除并重新插入空格

2024-10-03 02:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

从文本中删除空格,然后在执行必要的功能后,重新插入先前删除的空格,最有效的方法是什么?你知道吗

以下面的示例为例,下面是一个用于编码简单railfence密码的程序:

from string import ascii_lowercase

string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])

这将输出以下内容:

hlooltdyelwrdoa

这是因为它必须在编码文本之前删除间距。但是,如果现在要重新插入间距使其变为:

hlool tdyel wrdoa

最有效的方法是什么?你知道吗


Tags: 方法from文本import程序功能密码示例
3条回答

使用listjoin操作

random_string = "Hello World Today"
space_position = [pos for pos, char in enumerate(random_string) if char == ' ']
random_string = random_string.replace(" ", "").lower()
random_string = list(random_string[::2] + random_string[1::2])

for index in space_position:
    random_string.insert(index, ' ')

random_string = ''.join(random_string)
print(random_string)

正如其他评论员提到的,您需要记录空格的来源,然后将它们添加回

from string import ascii_lowercase
string = "Hello World Today"
# Get list of spaces
spaces = [i for i,x in enumerate(string) if x == ' ']
string = string.replace(" ", "").lower()
# Set string with ciphered text
ciphered = (string[::2] + string[1::2])
# Reinsert spaces
for space in spaces:
    ciphered = ciphered[:space] + ' ' + ciphered[space:]

print(ciphered)

你可以用str.split来帮助你。在空格上拆分时,剩余段的长度将告诉您拆分已处理字符串的位置:

broken = string.split(' ')
sizes = list(map(len, broken))

您将需要大小的累计和:

from itertools import accumulate, chain
cs = accumulate(sizes)

现在可以恢复空间:

processed = ''.join(broken).lower()
processed = processed[::2] + processed[1::2]

chunks = [processed[index:size] for index, size in zip(chain([0], cs), sizes)]
result = ' '.join(chunks)

这个解决方案不是特别直接或有效,但它确实避免了显式循环。你知道吗

相关问题 更多 >