为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

30秒到达战场 2023-08-08 17:02:42
这是我的代码,目前它在单独的行上打印解密的凯撒密码字符。有什么方法可以将它们作为字符串添加到一行上吗?此外,是否有一种可能的方法来实现 .isalpha() 来解释未加密消息中的空格和问号等。"""Cypher program."""import stringalphabet = string.ascii_lowercasemessage = "thequickbrownfoxjumpsoverthelazydog"key = 7for char in message:    new_char = key + (alphabet.index(char))    if new_char > 25:        new_char = new_char % 26    print(alphabet[new_char])我对 Python 很陌生,如果这是一个新手问题,我很抱歉。非常感谢任何好心人的帮助。
查看完整描述

2 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

您可以将alphabet[new_char]追加到列表中,然后使用 join 将其打印为字符串。下面的示例代码(经过编辑以让非字母数字的字符保留在原处):


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))


查看完整回答
反对 回复 2023-08-08
?
波斯汪

TA贡献1811条经验 获得超4个赞

"""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))


查看完整回答
反对 回复 2023-08-08
  • 2 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信