In this article we will discuss different ways to iterate or loop over all the characters of string in forward, backward direction and also by skipping over certain characters.

Iterate over string using for loop

Iterating over the string is simple using for loop and in operator i.e.

Output:

Iterate over string with index using range()

range(len (stringObj) ) function will generate the sequence from 0 to n -1 ( n is size of string) .  Now iterate over this sequence and for each index access the character from string using operator [] i.e.

It will print the string contents

Iterate over a portion of string only

To iterate over a portion of string like a sub string , we can use slicing operator to generate a sub string and then iterate over that sub string. To generate a slice we will use [] operator i.e.

string[start : stop : step size]

We can pass the start and stop index to generate a sub string and then we can iterate over it. For example, lets see how to iterate over the first 3 characters of string

Output:

Iterate over a string by skipping characters

Output:

Iterate over string in backward / reverse direction using slicing

In the slicing operator [] i.e.

string[start: stop : step size]

If we skip the start and stop index, then it will use the whole string for generating sub string. But if we pass step size as -1 then it will iterate over the current string in backward direction to generate a new string, that is the reverse of original string. Then iterate over this reversed string i.e.

It will print the string contents in reverse order :

Iterate over string in reverse using indexing :

Instead of generating a new reversed string and then iterating over that we can iterate over the current string in backward direction using indexing i.e.

It will print the string contents in reverse order

or we can use negative indexing to iterate over a string in backward direction i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.