gpt4 book ai didi

python - 将字符串添加到字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:00:06 26 4
gpt4 key购买 nike

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

最佳答案

Python 字符串是不可变的,因此您应该将变量名重新分配给一个新字符串。

其中带有“__”的函数通常不是您真正想要使用的。让解释器使用内置运算符/函数(在本例中为“+”运算符)为您进行调用。

所以,而不是:

self.finmix.__add__(fin)

我建议你试试:

self.finmix = self.finmix + fin

或等效和简洁的:

self.finmix += fin

如果您始终进行此类更改,您的问题可能会消失。

关于python - 将字符串添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6302580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com