For Loops 2 Strings - Lakelands Computing

Title
Go to content
For Loops part 2 - Looping over  / through Strings
In part 1 we saw how For loops can count between a start number and an end number. We can use this approach with Strings and Lists, using their index numbers instead of actual numbers for start and stop, and the beauty of it is you don't even need to include the index numbers, python understands what you mean:

  • word = "fishes"
  • for i in word:
    • print (i)

This would print out the letters of the word so "f","i","s","h","e","s" - run the trinket to see it.

When using for loops like this you can make them more user friendly by using something more descriptive than i;

  • word = "fishes"
  • for letter in word:
    • print (letter)

You can also add in a count to keep track of how many letters there are, or which letter is where (there are other ways to do this - but it is a useful technique when if is used as well - more on that below)

  • count = 0
  • word = "squirrel"
  • for letter in word:
    • print (letter)
    • count = count + 1
    • print (count)

You can use for loop to help you search for a particular character. To do this we need to use an if statement inside the loop:

  • bCount = 0
  • word = "bumblebee"
  • for letter in word:
    • if letter =="b":
      • bCount = bCount+1
  • print ("there a ", bCount, "b's in that word")

Take a look at the trinket, there is a more complex version of this type of searching there, as well as the other examples we've already looked at.  Python is used a lot for data processing and makes use of this searching method, along with string slicing to search through and divide up large text files - that isn't covered here though.
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content