将字符串添加到字符串中
我在把一个字符串加到另一个字符串上时遇到了问题。我刚开始学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
3 个回答
0
我在猜测,但大概是这样的:
self.finmix.__add__(fin)
#should be
self.finmix = self.finmix.__add__(fin)
1
我没有你问题的具体解决办法,但我有几个更一般的建议。
私有方法
.__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):
会更好。
3
Python中的字符串是不可变的,也就是说你不能直接修改它们。如果你想改变一个字符串,应该把这个变量重新指向一个新的字符串。
带有"__"的函数通常不是你真正想用的。让解释器帮你处理这些事情,使用内置的操作符或函数(在这个例子中就是"+"操作符)。
所以,不要这样做:
self.finmix.__add__(fin)
我建议你试试:
self.finmix = self.finmix + fin
或者可以用更简洁的方式:
self.finmix += fin
如果你在代码中都做这样的修改,你的问题可能就会解决了。