Python strings, lists and process string in for loop

Viewed 87

i am forcing myself to properly learn python, instead of just hacking on it when i want something. going thru a book, and i want to process in a for loop, thats working with a list:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
    #print(mage)
    #print(mage.title() + ", is now a master and a planwalker")
    s = mage.find("merlin")
    print(s)
print("script has Finished...")

can't find, the way to search for the string as it process in the for loop. so i can mess with it. (maybe i am slow :))

what would be a good way to find which item in the list is being processed so i can do something different with each one?

6 Answers

You can try this:

for mage in magicians:
  if mage=="....":
      <do whatever you want to do with mage>

you should be using an if statement as follows:

    magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
    #print(mage)
    #print(mage.title() + ", is now a master and a planwalker")
    if mage =="merlin":
        print(mage)
print("script has Finished...")

Indexing the list. like..

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']

length = len(magicians) 
for i in range(length): 
  #print(mage)
  #print(mage.title() + ", is now a master and a planwalker")
  if mage[i] == 'merlin':
    print(mage)
print("script has Finished...")

you can you this if you want to search for certain characters:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
    #print(mage)
    #print(mage.title() + ", is now a master and a planwalker")
    if"mer" in mage :
        print(mage)
print("script has Finished...")

You can print the index using enumerate:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for index, mage in enumerate(magicians):
    #print(mage)
    #print(mage.title() + ", is now a master and a planwalker")
    if mage == "merlin":
        print(mage, 'Index of it is', index)
print("Done.")

By tracking the index of the list ,we can find which item is being processed

Related