简体   繁体   English

在 Python 3.8 中将不同行上的字符打印成字符串

[英]Printing characters on different lines into a string in Python 3.8

Here's my code, at the moment it prints the decrypted Caesar Cypher characters all on seperate lines.这是我的代码,目前它在单独的行上打印解密的凯撒密码字符。 Is there any way to add them onto one line as a string ?有没有办法将它们作为字符串添加到一行中? Moreover is there a possible way to implement .isalpha() to account for spaces and questions marks etc in the uncrypted message.此外,有没有一种可能的方法来实现 .isalpha() 来解释未加密消息中的空格和问号等。

"""Cypher program."""
import string

alphabet = string.ascii_lowercase
message = "thequickbrownfoxjumpsoverthelazydog"
key = 7
for char in message:
    new_char = key + (alphabet.index(char))
    if new_char > 25:
        new_char = new_char % 26
    print(alphabet[new_char])

I am quite new to Python, very sorry if this is a newbie question.我对 Python 很陌生,如果这是一个新手问题,我很抱歉。

Many thanks to whomever is kind enough to help.非常感谢任何愿意提供帮助的人。

You can append alphabet[new_char] into a list and then use join to print it as string.您可以将字母 [new_char] 附加到列表中,然后使用 join 将其打印为字符串。 Sample code below (edited to let chars that are not alpha numeric to be left in place):下面的示例代码(编辑为让不是字母数字的字符留在原处):

import string

alphabet = string.ascii_lowercase
message = "the quick brow???nxa2 fox jumps over the lazy dog"
key = 7
lst=[]
for char in message:
    if char.isalpha() is True:
        new_char = key + (alphabet.index(char))
        if new_char > 25:
            new_char = new_char % 26
        lst.append(alphabet[new_char])
    else:
        lst.append(char)
print(''.join(i for i in lst))
"""Cypher program."""
import string

alphabet = string.ascii_lowercase
message = "thequick0brownfox jumpsoverthelazydog"

def transform(char,key):
    if char.isalpha():
       new_char = key + (alphabet.index(char))
       if new_char > 25:
           new_char = new_char % 26
       return alphabet[new_char]
    return char

key = 7

# faster string comprehension
decripted = [transform(char,key) for char in message]
  
print(decripted)
# or 

# "".join - puts all elements of an array toghether in a string using a separator
print("".join(decripted))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM