【发布时间】:2011-06-10 06:07:06
【问题描述】:
我在将一个字符串添加到另一个字符串时遇到问题。我是 Python 新手。
字符串无法记住我之前添加的值。
谁能帮帮我?以下是Python中的sn-p代码。
我的问题出在 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
【问题讨论】:
-
err... 你有没有机会指出你认为问题出在哪里?或者可能发布一个较小的示例......或者至少发布程序的输出和预期输出
-
请注意,添加两个字符串是一项相当昂贵的操作,因为它涉及创建一个新的字符串对象并将两个字符串的内容复制到其中。如果您执行大量此类操作并且速度很重要,请考虑使用 cStringIO 模块中的 StringIO 对象。