Iterate over characters in a string in python



Example # 1: Using simple iteration and range()

# Python program for iterating over line characters

 
# Code # 1

string_name = "pythonengineering"

 
# Loop over the line

for element in string_name:

print (element, end = `` )

print ( " " )

  

 
Code # 2

string_name = "GEEKS"

 
# Iterate by index

for element in range ( 0 , len (string_name)):

print (string_name [element])

Output:

 pythonengineering GEEKS 

Example # 2: Use enumerate()

# Python program to iterate over string characters

 

string_name = " Geeks "

  
# Loop over the line

for i, v in enumerate (string_name):

print (v)

Exit :

 G eeks 

Example # 3: iterating characters in reverse

# Python program to iterate over string characters

 
# Code # 1

string_name = "GEEKS"

 
# slice the line in reverse

for element in string_name [:: - 1 ]:

print (element, end = ` ` )

print ( `` )

 
Code # 2

string_name = "pythonengineering"

 
# Get line length

ran = len (string_name)

 
# using the reversed () function

for element in reversed ( range ( 0 , ran)):

print (string_name [element])

Output:

 SKEEG skeegrofskeeg 

Example # 4: Iterate over a specific set of elements.

Iterate over string_name by passing specific row index values.

# Python program to iterate over a specific set of elements.

string_name = " pythonengineering "

  
# string_name [start: end: step]

for element in string_name [ 0 : 8 : 1 ]: 

print (element, end = `` )

Output:

 geeksfor