简体   繁体   中英

Why is this printing first index?

Working on this problem for a python course and can't for the life of me figure out why this doesn't work. I'd rather it give me an error than print 0!

Problem gives me the variable x with the string shown and need to print the index of the first time y is used.

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

Code shown returns:

u is first seen in index =  0

Did you want index in x ? In that case, use x.index(o) where searches for o in 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

However, the correct way to write it is without the loop:

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'

print(y, "is first seen in index = ", x.index(y))

output:

u is first seen in index =  51

You're essentially having it look for 'u'.index('u')

y.index(o) should be x.index(o) for this example.

Do you need to iterate? If you keep your first 2 lines then use x.index(y) you will get the same result without using a while , for or if .

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
print(y, "is first seen in index = ", x.index(y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM