Python3.7:根据使用情况在int和str之间切换变量

Python3.7:根据使用情况在int和str之间切换变量,python,python-3.x,Python,Python 3.x,我正在开发python Caesar cypher(为了好玩,我知道这不是加密消息的好方法),我遇到了一个问题。当我运行第一位代码时,我得到一个错误,即replace()中的第一个参数必须是一个字符串,而不是一个整数,而前面已经是一个字符串(“TypeError:replace()参数1必须是str,而不是int”) 但是,每当我尝试将它用作字符串的标记时,它都会告诉我它不是int(“TypeError:字符串索引必须是整数”) 这是代码,提前谢谢。(代码还有几个部分,但我认为它们与问题无关。)

我正在开发python Caesar cypher(为了好玩,我知道这不是加密消息的好方法),我遇到了一个问题。当我运行第一位代码时,我得到一个错误,即
replace()
中的第一个参数必须是一个字符串,而不是一个整数,而前面已经是一个字符串(“TypeError:replace()参数1必须是str,而不是int”)

但是,每当我尝试将它用作字符串的标记时,它都会告诉我它不是int(“TypeError:字符串索引必须是整数”)

这是代码,提前谢谢。(代码还有几个部分,但我认为它们与问题无关。)

def find_str(s,char):
索引=0
如果字符在s中:
c=char[0]
对于ch in s:
如果ch==c:
如果s[index:index+len(char)]==char:
回报指数
指数+=1
返回-1
阿尔法类:
定义初始化(自我、消息、键):
self.fKey=key
self.msg=str(消息)
self.alpha=[]
self.spcLoc=[]
self.spcNum=0
self.encryptedMessage=str(self.msg)
def ENCMG(自我):
对于self.spcNum中的字母):
str.replace(字母,find_str(self.alpha,字母)+self.fKey,self.spcNum)
def main():
msg='这是斯巴达'
键=1
a=α(消息,键)
a、 encMsg()
这是一个for-each循环,在
self.spcNum
中循环每个值

比如说

for letter in ['a','b','c']:
   print(letter)
将打印字母
a
b
c

您可以迭代
self.spcNum
。因为它是一个整数(值为0),而不是一个列表

代码中还有其他问题

str.replace(letter, find_str(self.alpha,letter) + self.fKey, self.spcNum)
您使用此方法不正确

正确用法:

stringYouWantEdited = "hi, my name is DGGB, hi"
substringYouWantReplaced = "hi"
newSubstring = "hello"
numberOfTimesThisShouldHappen = 1


newString = stringYouWantEdited.replace(substringYouWantReplaced , newSubstring , numberOfTimesThisShouldHappen )
print(newString)

self.spcNum中的字母在
后面有一个右括号):
。对于范围内的字母(self.spcNum):,这可能是复制/粘贴错误,但您应该检查它。此外,如果是这种情况,
self.spcNum=0
将使代码不进入循环,并且不会引发错误。
stringYouWantEdited = "hi, my name is DGGB, hi"
substringYouWantReplaced = "hi"
newSubstring = "hello"
numberOfTimesThisShouldHappen = 1


newString = stringYouWantEdited.replace(substringYouWantReplaced , newSubstring , numberOfTimesThisShouldHappen )
print(newString)