Search code examples
pythonpytz

Find word index in string in python


I have a list and i want to find index of any words starting with Iran and print them.

import pytz
word = 'iran'
text = str(pytz.all_timezones).lower()
for t in text.split():
    if t.startswith(word):
       print(text[t.index(word)])

the output is 'a' and ',' but i need any word containing iran


Solution

  • Maybe you can use

    import pytz
    word = 'iran'
    text = [x.lower() for x in pytz.all_timezones]
    for t in text:
        if t.startswith(word):
            print(text.index(t))
    

    List comprehension and lower() is used to make a list the elements of which are strings.

    These elements are checked with startswith() and if its return value is True, its index is printed with index().

    Output:

    507