正如标题所说,我对如何在遍历字符串之后将其放回一行感到困惑。
现在我有这个:
for element in want_cyphered:
element = ord(element)
element = element + 13
element = chr(element)
print(element)
这将遍历want_cyphered字符串并打印它。这是一个用于密码和解密的函数。我想知道的是如何再次将迭代编译成实际的行?现在,我的打印是每行一个字符,但我希望它都在一行上。任何帮助都将不胜感激!使用python
Tags:
照办
end=”“部分告诉Python在末尾添加一个空字符串。end参数默认为新行,因此它在一行上打印每个字符。设置end=“”使其全部打印在一行上
创建一个变量并将元素附加到循环内的变量。循环结束时,打印结果
或者如果你真的想变得很花哨
其他答案没有错,但既然您使用的是Python,那么您也可以使用它擅长的东西(而且您的代码可能也会更快):
要分解它(假设您是Python新手):
''.join(list_of_parts)
获取字符串部分(字符或字符串)的列表,并使用开头的字符串(本例中为空字符串)将它们连接到一个字符串中您可以使用生成器表达式(一种非常好的迭代iterable的方法)生成该部分列表,如
[ch for ch in some_str]
,它将获得字符串中的字符列表我刚才把生成器放在方括号中,这样它就会变成一个实际的列表,但是当您只编写一个生成器作为某个函数的输入时,您可以传递生成器本身,而不需要像
''.join(ch for ch in some_str)
这样的括号,它基本上什么都不做。它把绳子拆开,然后再放回一起但是您也可以将操作应用于该生成器的元素,因此您可以使用
chr(ord(ch) + 13)
填充列表,而不仅仅是ch
,这是您希望应用的密码把所有这些放在一起,你会得到:
相关问题 更多 >
编程相关推荐