首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python加解密

Python加解密
EN

Stack Overflow用户
提问于 2017-03-15 05:03:27
回答 1查看 2.2K关注 0票数 0

我试图加密一个用户输入信息。

我的代码:

代码语言:javascript
复制
#encrypt
user_input = input ("Enter string: ")
for char in user_input: #for every character in input
    cipher_num = (ord(char))+3%26 #using ordinal to find the number
    cipher= ''
    cipher = chr(cipher_num) # using chr to convert back to a letter
    cipher_text = '' #add all values to string
    cipher_text = (cipher_text+cipher)
print (cipher_text)

#decrypt
for char in cipher_text: #for every character in the encrpted text
    decrypt_num = (ord(char))-3%26
    decrypt= ''
    decrypt = chr(decrypt_num)
    decrypt_text = ''
    decrypt_text = (decrypt_text+decrypt)
print(decrypt_text)

我收到的输出是-

输入字符串: abc

F

C

为什么它只给出字符串中最后一个字符的加密值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-15 05:08:13

在你的循环中,你有

代码语言:javascript
复制
 cipher_text = '' #add all values to string

cipher_text重置为空字符串。您的代码在每个循环中都写着:“空cipher_text并在其中放一个字符”。

您需要将这条线移出for循环。

您的代码应该如下所示:

代码语言:javascript
复制
cipher_text = ''  # initialise the string
for char in user_input:
    cipher_num = (ord(char))+3%26
    cipher= ''   # you don't need this line as the next one overwrites the variable
    cipher = chr(cipher_num)
    cipher_text = cipher_text + cipher
    # you can shorten the line above to: cipher_text += cipher

decrypt_text也是如此。

有许多方法可以简化这段代码,并使其更加pythonic,但这是另一个问题:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42801478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档