我在將字符串添加到另一個字符串時遇到問題。我是Python的新手。將字符串添加到字符串
該字符串不記得我添加的以前的值。
任何人都可以幫助我?以下是Python中的代碼片段。
我的問題是加密的,而環()。
感謝提前。
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
err ...你指出你認爲問題出在哪裏的任何機會?或者發佈一個更小的例子......或者至少發佈程序的輸出和期望輸出 – 2011-06-10 06:16:58
請注意,添加兩個字符串是一個相當昂貴的操作,因爲它涉及創建一個新的字符串對象並複製這兩個字符串的內容串入它。如果你做了很多這些操作並且速度有一些重要性,可以考慮使用cStringIO模塊中的[StringIO](http://docs.python.org/library/stringio.html)對象。 – 2011-06-10 09:42:29