在Python中,string.replace不返回修改后的字符串
我试图用Python编写一个加密程序,为每次使用创建一个新的“密钥”。那部分很好用。我遇到的问题是实际的加密。我的代码不会加密用户提供的字符串。它似乎一直工作到for循环,我不明白为什么它不工作在Python中,string.replace不返回修改后的字符串,python,Python,我试图用Python编写一个加密程序,为每次使用创建一个新的“密钥”。那部分很好用。我遇到的问题是实际的加密。我的代码不会加密用户提供的字符串。它似乎一直工作到for循环,我不明白为什么它不工作 import keycreater as k k = k.keycreater() print(k.key) class encrypt(object): ''' This class is used to actually encrypt the string '''
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)
您的for循环工作正常。但是,正如Jornsharpe所说,
string
是不可变的。此外,循环和替换的将返回错误的结果
您应该将字符串拆分为个字符,并使用键替换每个字符。之后,您可以使用''.join(characters)
创建新字符串
encode_string = []
for s in user_string:
encode_string.append(convert(s))
return ''.join(encode_string)
或与map
加入(映射(转换,用户字符串))
您还可以从模块导入字母表。字符串是不可变的,
self.new.replace(字母表[x],键[x])
不会更改self.new
。尝试self.new=self.new.replace(…)
。此外,考虑如果将来的替换与先前的替换重叠,将会发生什么?您是否尝试了<代码> > <代码>循环> < <代码>打印< /代码>语句?代码>打印是你的朋友。回到dos和Windows 3.11时代,我只有printf
。@liamw309,请将答案标记为已接受。