Python Forum

Full Version: How to do String match
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have the following array of string:

kaman
veeru
sri
balc
kaman
tryi
yua
sri

Now, I want to the two thing
Question1:
I want to find the locations(index) of "sri" in the list

Queastion2:
I want to know if the given name exist in the list or not (for example: "kaman"  exist in the list or not)
Thanks in advance,
For more details about lists you can check Lists tutorial
Output:
>>> a_list = ['a', 'b', 'c'] >>> a_list.index('b') 1 >>> 'c' in a_list True
Do not use private messages to seek help, use regular posts.

If you need to get indices of all positions of particular term in a list, you can iterate over that list and check its elements and eventually add index to your "list of matching indices". And you can shorten it with a list comprehension:
Output:
>>> a_list = list("sdflksdjfajfd") >>> a_list ['s', 'd', 'f', 'l', 'k', 's', 'd', 'j', 'f', 'a', 'j', 'f', 'd'] >>> occurences_of_f = [idx for idx, item in enumerate(a_list) if item == "f"] >>> occurences_of_f [2, 8, 11]