Python Forum
How to do String match - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to do String match (/thread-2680.html)



How to do String match - SriRajesh - Apr-02-2017

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,


RE: How to do String match - zivoni - Apr-02-2017

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



RE: How to do String match - zivoni - Apr-02-2017

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]