Python列表索引值未正确返回

2024-04-19 11:57:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我试图得到值“bad”的索引,由于某种原因它抛出了一个错误。你知道吗

>>> s = "This dinner is not that bad!"
>>> l = s.split()
>>> bad_index_value = l.index('bad')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

Tags: 字符串inmostindexthatisvalue错误
3条回答

实际上,您的列表中没有bad它的bad!。如果要查找bad的索引,可以使用'!'剥离元素:

>>> s = "This dinner is not that bad!"
>>> s.strip().split()
['This', 'dinner', 'is', 'not', 'that', 'bad!']
>>> 
>>> l=s.strip('!').split()
>>> l.index('bad')
5
>>> s = "This dinner is not that bad !"
>>> l = s.split()
>>> bad_index_value = l.index('bad') # will give you the index.

从技术上讲,bad不存在于您的输入This dinner is not that bad!,它的bad!

>>> import re
>>> s = "This dinner is not that bad!"
>>> re.sub(r'[^\w\s]','',s).split().index('bad')
5
>>>

相关问题 更多 >