Iterate 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.
For, strings. 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
An example. 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
List. 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.