Python for: Loop Over String CharactersIterate over the characters in a string with for. Use enumerate, reversed and range.
For. In Python we find lists, strings, ranges of numbers. We often want to loop over (iterate through) these values. With the for-loop this is possible.
We often loop over characters. This can be done with a for-loop. We can directly loop over a string. Or we can use a for-loop with the range method to loop over indexes.List forDictionary for
Here is a program that loops over a string. The value "abc" has 3 letters in it—3 characters. We use the for-keyword.Built-ins
Tip: If you need to get adjacent characters, or test many indexes at once, the for-loop that uses range() is best.
Python program that uses for-loop on strings
s = "abc"
# Loop over string.
for c in s:
# Loop over string indexes.
for i in range(0, len(s)):
a Loop 1
a Loop 2
A for-loop acts upon a collection of elements, not a min and max. In for, we declare a new variable. And after the in-keyword, we specify the collection we want to loop over.In
Note: It is possible to create a new collection, as with range(), immediately for the for-loop to act upon.range
And: This makes the for-loop more similar to the syntax forms in other languages.
Python program that shows for-loop
names = ["Sarah", "Rakesh", "Markus", "Eli"]
# Loop over list.
for name in names:
This receives an iterable. It returns each index and the associated value with each index. The result is an object, which has two parts (index, value). Here we use it on a list.Enumerate
Index: Enumerate here returns an index of 0 for "boat." This makes sense as the value "boat" is the first element in the list.
Python program that uses enumerate, list
list = ["boat", "car", "plane"]
# Call enumerate to loop over indexes and values.
for i, v in enumerate(list):
Reverse. We can loop over any sequence in reverse. We use the reversed() method. This returns a view of the sequence in inverted order. It does not change the original sequence.
Python program that uses reversed
# Use reversed on a range.
for i in reversed(range(0, 3)):
# Display the index.
One-line syntax. Typically a loop uses 2 or more lines, but we can place the entire loop on a single line if needed. This can make short loops easier to read (and files easier to edit).
Python program that uses for-loop, one-line
# Use single-line for-loop syntax.
for number in range(0, 10, 2): print(number)
We can use the iter built-in to create custom for-loop logic. The iter method (and next) can be used to iterate over a collection in a special way.iter
A review. With the for-loop we can loop over collections like lists. But we can also loop over the characters in a string. This keyword is versatile in the types it handles.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.