我是编程世界的新手(你可能可以从我的低效代码问题看出来).&

我的代码是用来判断字符串中的两个后续字符是否相同.我不明白为什么这两个伪变量在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都被初始化为整数.

推荐答案

当你执行for i in string:时,你基本上是用变量'string'的字符串迭代器来迭代你的i变量.这意味着你正在遍历字符串中的每个字母,并将字符存储在"i"中.正确的方法是使用enumerate.你也可以像range(len(string))这样使用range.下面是一个你正在try 做的工作示例:

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'越界.使用double for循环可以避免这个问题.

Python相关问答推荐

如何在箱形图中添加绘制线的传奇?

优化pytorch函数以消除for循环

如何让程序打印新段落上的每一行?

用Python解密Java加密文件

基于字符串匹配条件合并两个帧

Python,Fitting into a System of Equations

Pandas DataFrame中行之间的差异

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

改进大型数据集的框架性能

计算分布的标准差

Django RawSQL注释字段

计算天数

如何使用Numpy. stracards重新编写滚动和?

Maya Python脚本将纹理应用于所有对象,而不是选定对象

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

如何获得3D点的平移和旋转,给定的点已经旋转?

如何在Airflow执行日期中保留日期并将时间转换为00:00

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

Python如何导入类的实例

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,