使用stings列表进行python加密和解密[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我正在编写一个代码,用于加密用户输入的String列表。这些列表将被加密,然后将被解密。但是一旦它到达加密部分就会给我这个错误。

回溯(最近一次调用最后一次):文件“C:/Users/dana/Desktop/q2.py”,第16行,在x = ord(c)中TypeError:ord()需要一个字符,但找到长度为4的字符串

我确信即使在解密部分也会出现同样的错误。

这是我的代码:

    # Encryption
list1=[]
list2=[]
i = 0
while not(False):
    plain_text = input ("Enter any string ")
    if (plain_text !='q'):
        list1.append(plain_text)
        i=i+1
    else:
        break



encrypted_text = ""
for c in list1:
    x = ord(c)
    x = x + 1
    c2 = chr(x)
    encrypted_text = encrypted_text + c2
print(encrypted_text)

#Decryption
encrypted_text = "Uijt!jt!b!uftu/!BCD!bcd"

plain_text = ""
for c in encrypted_text:
    x = ord(c)
    x = x - 1
    c2 = chr(x)
    plain_text = plain_text + c2
print(plain_text)
list2=[encrypted_text]
print(plain_text)
print("the original msgs are :" , list1)
print("the encrypted msgs are :" ,list2)
python python-3.x list encryption
2个回答
1
投票

ord()采用单个字符

for c in list1:
 x = ord(c)

但上面的循环返回字符串为C,这就是为什么你得到错误更正代码

list1=[]
list2=[]
i = 0
while not(False):
    plain_text = input ("Enter any string ")
    if (plain_text !='q'):
        list1.append(plain_text)
        i=i+1
    else:
        break



encrypted_text = ""
for c in list1: #Changed Code
  for c1 in c:
    x = ord(c1)
    x = x + 1
    c2 = chr(x)
    encrypted_text = encrypted_text + c2
print(encrypted_text)

#Decryption
encrypted_text = "Uijt!jt!b!uftu/!BCD!bcd"

plain_text = ""
for c in encrypted_text:
    x = ord(c)
    x = x - 1
    c2 = chr(x)
    plain_text = plain_text + c2
print(plain_text)
list2=[encrypted_text]
print(plain_text)
print("the original msgs are :" , list1)
print("the encrypted msgs are :" ,list2)

2
投票

list1包含用户为响应input提示而输入的任何字符串。

然后你的第一个for循环遍历list1c承担了list1元素的价值观。然后你在ord上使用c。我希望你的意图是在ord的元素上使用c。尝试在某处添加一个额外的循环。

另外,请考虑将代码组织到函数中。

© www.soinside.com 2019 - 2024. All rights reserved.