如果string在list [0]中,python list.index('')无法在列表中找到字符串 - 为什么?我怎么找到它?

时间:2013-05-10 07:30:23

标签: python list indexing

我疯了吗?

在我的测试中,如果字符串在列表[0]中,则python list.index('')无法在列表中找到字符串!!!

为什么呢?我怎么找到它?

这是我的示例代码:

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]

这给我以下结果:

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

我想我必须遗漏一些非常明显的东西...但是无法弄明白或找到答案...请帮我通过搜索字符串找到list1中的'WTF'或list2中的'1'... ..

1 个答案:

答案 0 :(得分:3)

执行if list1.index('1')时,您正在测试该列表中'1'的索引是否为布尔值true。它的索引为零,这是布尔值false。所以你的if块没有运行。

如果您想知道它是否存在,请执行if '1' in list1