[英]adding string to a string
我在将字符串添加到另一个字符串时遇到问题。 我是 Python 的新手。
该字符串无法记住我之前添加的值。
谁能帮助我? 以下是 Python 中的代码片段。
我的问题出在 encrypt() 的 while 循环中。
提前致谢。
class Cipher:
def __init__(self):
self.alphabet = "abcdefghijklmnopqrstuvwxyz1234567890 "
self.mixedalpha = ""
self.finmix = ""
def encrypt(self, plaintext, pw):
keyLength = len(pw)
alphabetLength = len(self.alphabet)
ciphertext = ""
if len(self.mixedalpha) != len(self.alphabet):
#print 'in while loop'
x = 0
**while x < len(self.alphabet):
mixed = self.mixedalpha.__add__(pw)
if mixed.__contains__(self.alphabet[x]):
print 'already in mixedalpha'
else:
add = mixed.__add__(str(self.alphabet[x]))
lastIndex = len(add)-1
fin = add[lastIndex]
print 'fin: ', fin
self.finmix.__add__(fin)
print 'self.finmix: ', self.finmix
x+=1**
print 'self.finmix: ', self.finmix
print 'self.mixedalpha: ', self.mixedalpha
for pi in range(len(plaintext)):
#looks for the letter of plaintext that matches the alphabet, ex: n is 13
a = self.alphabet.index(plaintext[pi])
#print 'a: ',a
b = pi % keyLength
#print 'b: ',b
#looks for the letter of pw that matches the alphabet, ex: e is 4
c = self.alphabet.index(pw[b])
#print 'c: ',c
d = (a+c) % alphabetLength
#print 'd: ',d
ciphertext += self.alphabet[d]
#print 'self.alphabet[d]: ', self.alphabet[d]
return ciphertext
Python 字符串是不可变的,因此您应该将变量名称重新分配给新字符串。
带有“__”的函数通常不是您真正想要使用的。 让解释器使用内置的运算符/函数(在本例中为“+”运算符)为您进行调用。
所以,而不是:
self.finmix.__add__(fin)
我建议你试试:
self.finmix = self.finmix + fin
或等效且简洁的:
self.finmix += fin
如果您始终进行这种更改,您的问题可能会 go 消失。
我没有解决您的问题的方法,但我有一些更一般的建议。
私有方法.__add__
和.__contains__
并不意味着直接使用。 您应该直接使用+
和in
运算符。
而不是通过 while 循环self.alphabet
的索引......
while x < len(self.alphabet): print self.alphabet[x] x += 1
你可以遍历字母
for letter in self.alphabet: print letter
class Cipher:
触发一种不适用于某些较新功能的向后兼容模式。 指定class Cipher(object):
会更好。
我猜但以下内容:
self.finmix.__add__(fin)
#should be
self.finmix = self.finmix.__add__(fin)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.