为什么要打印第一个索引?

在 python 课程中解决这个问题,但我终生无法弄清楚为什么这行不通。我宁愿它给我一个错误也不愿打印 0!


问题给了我显示的字符串的变量x,需要打印第一次y使用的索引。


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 = ", y.index(o))

            i += 1

显示的代码返回:


u is first seen in index =  0


Cats萌萌
浏览 124回答 3
3回答

心有法竹

你想要索引x吗?在这种情况下,使用x.index(o)where 搜索oin x。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 = ", 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

慕桂英546537

您实际上是在寻找'u'.index('u')y.index(o)应该是x.index(o)这个例子。

FFIVE

你需要迭代吗?如果您保留前 2 行然后使用,您将在不使用,或 的情况下x.index(y)获得相同的结果。whileforifx = 'Poisson geometry plays an important role in noncommutative geometry.'y = 'u'print(y, "is first seen in index = ", x.index(y))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python