简体   繁体   中英

python list.index('') fails to find string in list if string is in list[0] - why? how do i find it?

Am I going mad?

In my tests python list.index('') fails to find string in list if string is in list[0]!!!

why? how do i find it?

Here is my example code:

list1 = ['WTF', '2.09', '\xc2\x80document.write(CurrencyFormat(Currency.convert((209/100),"GBP","EUR")));','0.00', 'Feminised', '6.88', '\xc2\x80document.write(CurrencyFormat(Currency.convert((688/100),"GBP","EUR")));', 'Regular', 'x10', '20.90', '\xc2\x80document.write(CurrencyFormat(Currency.convert((2090/100),"GBP","EUR")));', 'Feminised', 'x12', '82.56', '\xc2\x80document.write(CurrencyFormat(Currency.convert((8256/100),"GBP","EUR")));']
list2 = ['1','2','3','4','5', '1']
if list1.index('0.00'):
    print "I found 0.00 in list 1 but if its in position[0], I cannot find it using index('0.00') - even it appears twice what gives?"
if list2.index('1'):
    print 'weird'
else:
    print 'I did not find 1 in list 2 even thought it is definitely there (twice infact)... WTF?'
print 'I can find it like this but I want to search by string >>> ' + list2[0]
print 'Or like this like this but I want to search by string >>> ' + list2[-1]

This give me the following result:

I found 0.00 in list 1 but if its in position[0], I cannot find it using index('0.00') - even it appears twice what gives?
I did not find 1 in list 2 even thought it is definitely there (twice infact)... WTF?
I can find it like this but I want to search by string >>> 1
Or like this like this but I want to search by string >>> 1

I think I must be missing something very obvious... but cannot figure it out or find an answer... please help me find 'WTF' in list1 or '1' in list2 by searching for the string.....

When you do if list1.index('1') , you are testing whether the index of '1' in that list is boolean true. Its index is zero, which is boolean false. So your if block doesn't run.

If you want to know if it's in there, just do if '1' in list1 .

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