adding string to a string
I have a problem adding a string to another string. I am new to Python.
The string cannot remember the previous values I added.
Anyone who can help me? The following is the code snippet in Python.
My problem is in the while loop of encrypt().
THANKS IN ADVANCE.
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.alph开发者_如何学JAVAabet[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 strings are immutable, so you should reassign the variable name to a new string.
Functions with "__" in them are not normally what you really want to use. Let the interpreter make that call for you by using the built in operators/functions (in this case the "+" operator).
So, instead of:
self.finmix.__add__(fin)
I suggest you try:
self.finmix = self.finmix + fin
or the equivalent and terser:
self.finmix += fin
If you make this sort of change throughout, your problem will probably go away.
I don't have a solution to your problem, but I have a couple of more general suggestions.
The private methods
.__add__
and.__contains__
aren't meant to be used directly. You should use the the+
andin
operators directly instead.Instead of going through the indexes of
self.alphabet
with a while loop...while x < len(self.alphabet): print self.alphabet[x] x += 1
you could just iterate over the letters
for letter in self.alphabet: print letter
class Cipher:
triggers a sort of backwards-compatibility mode that doesn't work with some newer features. Specifyingclass Cipher(object):
would be better.
I'm guessing but the following:
self.finmix.__add__(fin)
#should be
self.finmix = self.finmix.__add__(fin)
精彩评论