在 python 课程中解决这个问题,但我终生无法弄清楚为什么这行不通。我宁愿它给我一个错误也不愿打印 0!问题给了我显示的字符串的变量x,需要打印第一次y使用的索引。x = 'Poisson geometry plays an important role in noncommutative geometry.'y = 'u'i = 0while i == 0: for o in x: if o == y: print(y, "is first seen in index = ", y.index(o)) i += 1显示的代码返回:u is first seen in index = 0
3 回答

心有法竹
TA贡献1866条经验 获得超5个赞
你想要索引x吗?在这种情况下,使用x.index(o)where 搜索oin x。
x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
i = 0
while i == 0:
for o in x:
if o == y:
print(y, "is first seen in index = ", x.index(o))
i += 1
然而,正确的写法是没有循环:
x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
print(y, "is first seen in index = ", x.index(y))
输出:
u is first seen in index = 51

FFIVE
TA贡献1797条经验 获得超6个赞
你需要迭代吗?如果您保留前 2 行然后使用,您将在不使用,或 的情况下x.index(y)获得相同的结果。whileforif
x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
print(y, "is first seen in index = ", x.index(y))
添加回答
举报
0/150
提交
取消