You can do it like this with index()
on the tokens
list:
punc = ['.', '!', '?']
tokens = ['today', 'i', 'went', 'to', 'the', 'park', '.', 'it', 'was', 'great', '!']
for p in punc:
if p in tokens:
print(p, tokens.index(p), sep=" index is: ")
else:
print(p, 'not found', sep=' ')
This code will print all the punc index in tokens, if exists.
With list comprehension:
[print(p, tokens.index(p), sep=" index is: ") if p in tokens else print(p, 'not found', sep=' ') for p in punc]
Output:
. index is: 6
! index is: 10
? not found
In case you just want to check the first item and not the entire punc
list:
print(tokens.index(punc[0]) if punc[0] in tokens else 'not found')
OUTPUT:
6
The usage of [index()
] can generate a ValueError
exception when the element is not in the list:
Exception has occurred: ValueError
'?' is not in list
In you case this can happend for the value ?
that is not present in tokens
.
To solve this you have two simple ways:
- Check if the item is in list like:
'?' in tokens
(This is the clean/redable approach)
- Wrap the
.index()
call inside a try/except
and manage it. (This is the fast approach)