0

I have a string and Im trying to get the index of value "bad" and for some reason it throws me an error.

>>> 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
0

5 Answers 5

2

Actually you have not bad in your list its bad!. if you want to find the index of bad you can strip the element with '!':

>>> s = "This dinner is not that bad!"
>>> s.strip().split()
['This', 'dinner', 'is', 'not', 'that', 'bad!']
>>> 
>>> l=s.strip('!').split()
>>> l.index('bad')
5
Sign up to request clarification or add additional context in comments.

Comments

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

Technically bad is not present in your input This dinner is not that bad!, its bad!

2 Comments

But this is not the op's input.
Yes, i am telling him why his case failed and which one will pass so that he can know issue by himself. I gave example for his expected o/p.
0
>>> import re
>>> s = "This dinner is not that bad!"
>>> re.sub(r'[^\w\s]','',s).split().index('bad')
5
>>>

Comments

0

You can use re.split() instead of string.split(). The use of regular expressions allows specifying both the ! and whitespace (\s) as a delimiter:

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

Note that l now contains a trailing empty string (because one of the delimiters is at the end of the string):

>>> l
['This', 'dinner', 'is', 'not', 'that', 'bad', '']

If necessary, you can use a list comprehension to remove it:

>>> l= [x for x in re.split("[!\s]", s) if x]
>>> l
['This', 'dinner', 'is', 'not', 'that', 'bad']

Comments

-1

No need to split the string into a list just run

>>> s = "This dinner is not that bad!"
>>> s.find("bad")
24  # s[24] = 'b'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.