Python - 为什么我的代码返回 TypeError

问题描述 投票:0回答:1

我是编程世界的新手(你可能可以通过我低效的代码和问题看出)。

我的代码旨在检查字符串中的两个后续字符是否相同。我不明白为什么在 if 语句中引用这两个虚拟变量时会触发 TypeError (if string[i] == string[j]:)。它们已被初始化为 int - 为什么 python 在 if 语句中使用时似乎将其解释为 str 类型?

感谢您的宝贵时间。

#Get string from user
string = str(input("Enter a phrase: "))

#initialise i and the empty string doubleoccurrences
i = 0
j = i + 1

doubleOccurrences = str("N/A")

#loop through the string, which checks if two consecutive characters match
for i in string:
    if string[i] == string[j]:
        doubleOccurrences = doubleOccurrences.replace("N/A","")
        doubleOccurrences = (doubleOccurrences + string[i] + string[j])
        j = j + 1
    else:
         doubleOccurrences = doubleOccurrences
         j = j + 1

#print the output
print("Your input contains the following double occurrences: " + doubleOccurrences)


我期待 python 来解释

if string[i] == string[j]:

检查索引 i 处的字符是否等于索引 j 处的字符,假设 i 和 j 都已初始化为整数。

python for-loop if-statement typeerror
1个回答
0
投票

当你这样做时

for i in string:
,你基本上是用变量“string”的字符串迭代器覆盖你的 i 变量。这意味着您将遍历字符串中的每个字母并将该字符存储在“i”中。正确的方法是使用“枚举”。您还可以使用范围(len(字符串))。这是您正在尝试执行的操作的示例:

string = str(input("Enter a phrase: "))

doubleOccurrences = str("N/A")

#loop through the string, which checks if two consecutive characters match
for i in range(len(string)):
    for j in range(i + 1, len(string)):
        if string[i] == string[j]:
            doubleOccurrences = doubleOccurrences.replace("N/A","")
            doubleOccurrences = (doubleOccurrences + string[i] + string[j])
        else:
            doubleOccurrences = doubleOccurrences

#print the output
print("Your input contains the following double occurrences: " + doubleOccurrences)

请注意,我不确定你到底想做什么,所以我没有确保结果是正确的结果,我只是确保它运行。我还必须修改你的一些逻辑,因为你没有考虑到“j”出界。使用双 for 循环可以避免这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.