从文本中删除空格,然后在执行必要的功能后,重新插入先前删除的空格,最有效的方法是什么?你知道吗
以下面的示例为例,下面是一个用于编码简单railfence密码的程序:
from string import ascii_lowercase
string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
这将输出以下内容:
hlooltdyelwrdoa
这是因为它必须在编码文本之前删除间距。但是,如果现在要重新插入间距使其变为:
hlool tdyel wrdoa
最有效的方法是什么?你知道吗
使用
list
和join
操作正如其他评论员提到的,您需要记录空格的来源,然后将它们添加回
你可以用
str.split
来帮助你。在空格上拆分时,剩余段的长度将告诉您拆分已处理字符串的位置:您将需要大小的累计和:
现在可以恢复空间:
这个解决方案不是特别直接或有效,但它确实避免了显式循环。你知道吗
相关问题 更多 >
编程相关推荐