我正在尝试在Python中创建一个加密程序,为每次使用创建一个新的“密钥”。那部分工作正常。我遇到问题的部分是实际加密。我的代码不会加密用户提供的字符串。它似乎一直工作到for循环,我不明白为什么它不起作用。
import keycreater as k
k = k.keycreater()
print(k.key)
class encrypt(object):
'''
This class is used to actually encrypt the string
'''
def __init__(self):
'''
This method is used to initialize the class.
Attributes: initial (what the user wants encrypted), new (the string after it is encrypted).
'''
self.initial = []
self.new = ''
def getstr(self):
'''
This method gets what the user wants to encrypt.
Attributes: initial (what the user wants encrypted).
'''
self.initial = raw_input('What would you like to encrypt? ')
def encrypt(self):
'''
This method takes the string that the user wants encrypted and encrypts it with a for loop.
Attributes: alphabet (list of characters), key (key), new (encrypted string).
'''
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9']
key = k.key
self.new = self.initial.lower()
for x in range(0,35):
self.new.replace(alphabet[x],key[x])
a = encrypt()
a.getstr()
a.encrypt()
print(a.new)
答案 0 :(得分:2)
你的for循环工作正常。但jonrsharpe说,string
是不变的。此外,您的for-loop and replace
也会返回错误的结果。
您应该将字符串拆分为字符,并使用键替换每个字符。之后,您可以使用''.join(characters)
创建新字符串。
encode_string = []
for s in user_string:
encode_string.append(convert(s))
return ''.join(encode_string)
或与map
''.join(map(convert, user_string))
您也可以从string模块中导入字母。