温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Python 3.7 : Variable switching between int and str depending on usage
python python-3.x

其他 - Python 3.7:根据用法在int和str之间进行变量切换

发布于 2020-03-27 15:54:00

我正在使用python Caesar密码(出于娱乐目的,我知道这不是加密消息的好方法),但遇到了问题。当我运行第一部分代码时,我收到一条错误消息,当第一个arg in replace()必须是一个字符串,而不是整数,当它已经出现在字符串中时(“ TypeError:replace()参数1必须为str,而不是int”)。

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

这是代码,在此先感谢。(代码中还有更多部分,但我认为它们与问题无关。)

def find_str(s, char):

    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

class Alpha:

    def __init__(self, message, key):

        self.fKey = key
        self.msg = str(message)
        self.alpha = []
        self.spcLoc = []
        self.spcNum = 0
        self.encryptedMessage = str(self.msg)

    def encMsg(self):

        for letter in self.spcNum):
            str.replace(letter, find_str(self.alpha,letter) + self.fKey, self.spcNum) 

def main():

    msg = 'This is sparta'
    key = 1

    a = Alpha(msg, key)
    a.encMsg()

查看更多

查看更多

提问者
DGGB
被浏览
21
7,105 2020-01-31 23:19
for letter in self.spcNum:

这是一个for-each循环,循环遍历中的每个值self.spcNum

例如

for letter in ['a','b','c']:
   print(letter)

将打印出字母abc

不能迭代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)