Change language

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 

Iterate over characters in a string in python Python functions: Questions

Iterate over characters in a string in python String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method