我在将字符串添加到另一个字符串时遇到问题。我是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