我是编程世界的新手(你可能可以从我的低效代码问题看出来).&
我的代码是用来判断字符串中的两个后续字符是否相同.我不明白为什么这两个伪变量在if语句中被引用时会触发TypeError(if string [i]== string [j]:).它们被初始化为int—为什么python在if语句中使用时会将其解释为string类型?
耽误您时间,实在对不起.
#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都被初始化为整数.