TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Iterate Strings in Python (5 Ways)
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Iterate Strings in Python (5 Ways)

Last updated: Nov 05, 2023 12:08 am
By Meenakshi Agarwal
Share
7 Min Read
Multiple Ways to Iterate Strings in Python
Multiple Ways to Iterate Strings in Python
SHARE

In this tutorial, you will find out different ways to iterate strings in Python. You could use a for loop, range in Python, a slicing operator, and a few more methods to traverse the characters in a string.

Contents
1. Using for loop to traverse a string2. Python range to iterate over a string3. Slice operator to iterate strings partially4. Traverse the string backward using the slice operator5. Use indexing to iterate strings backwardSummary – Program to iterate over strings char by char

Multiple Ways to Iterate over Strings in Python

The following are various ways to iterate the chars in a Python string.

1. Using for loop
2. Python range function
3. Using the slice operator partially
4. Traverse the string backward using the slice operator
5. By using the indexing method

Let’s first begin with the “for loop” method.

1. Using for loop to traverse a string

It is the most prominent and straightforward technique to iterate strings. Follow the below sample code:

"""
Python Program:
 Using for loop to iterate over a string in Python
"""
string_to_iterate = "Data Science"
for char in string_to_iterate:
   print(char)

The result of the above coding snippet is as follows:

D
a
t
a

S
c
i
e
n
c
e

2. Python range to iterate over a string

Another quite simple way to traverse the string is by using the Python range function. This method lets us access string elements using the index.

Go through the sample code given below:

"""
Python Program:
 Using range() to iterate over a string in Python
"""
string_to_iterate = "Data Science"
for char_index in range(len(string_to_iterate)):
   print(string_to_iterate[char_index])

The result of the above coding snippet is as follows:

D
a
t
a

S
c
i
e
n
c
e

3. Slice operator to iterate strings partially

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and we can iterate over it partially.

The [] operator has the following syntax:

# Slicing Operator
string [starting index : ending index : step value]

To use this method, provide the starting and ending indices along with a step value and then traverse the string. Below is the example code that iterates over the first six letters of a string.

"""
Python Program:
 Using slice [] operator to iterate over a string partially
"""
string_to_iterate = "Python Data Science"
for char in string_to_iterate[0 : 6 : 1]:
   print(char)

The result of the above coding snippet is as follows:

P
y
t
h
o
n

You can take the slice operator usage further by using it to iterate over a string but leaving every alternate character. Check out the below example:

"""
Python Program:
 Using slice [] operator to iterate over a specific parts of a string
"""
string_to_iterate = "Python_Data_Science"
for char in string_to_iterate[ :  : 2]:
   print(char)

The result of the above coding snippet is as follows:

P
t
o
_
a
a
S
i
n
e

4. Traverse the string backward using the slice operator

If you pass a -ve step value and skip the starting as well as ending indices, then you can iterate in the backward direction. Go through the given code sample.

"""
Python Program:
 Using slice [] operator to iterate string backward
"""
string_to_iterate = "Machine Learning"
for char in string_to_iterate[ :  : -1]:
   print(char)

The result of the above coding snippet is as follows:

g
n
i
n
r
a
e
L

e
n
i
h
c
a
M

5. Use indexing to iterate strings backward

The slice operator first generates a reversed string, and then we use the for loop to traverse it. Instead of doing it, we can directly use the indexing method to traverse the string backward.

"""
Python Program:
 Using indexing to iterate string backward
"""
string_to_iterate = "Machine Learning"
char_index = len(string_to_iterate) - 1
while char_index >= 0:
   print(string_to_iterate[char_index])
   char_index -= 1

The result of the above coding snippet is as follows:

g
n
i
n
r
a
e
L

e
n
i
h
c
a
M

Alternatively, we can pass the -ve index value and traverse the string backward. See the below example.

"""
Python Program:
 Using -ve index to iterate string backward
"""
string_to_iterate = "Learn Python"
char_index = 1
while char_index <= len(string_to_iterate):
   print(string_to_iterate[-char_index])
   char_index += 1

The result of the above coding snippet is as follows:

n
o
h
t
y
P

n
r
a
e
L

Summary – Program to iterate over strings char by char

Let’s now consolidate all examples inside the Main() function and execute from there.

"""
Program:
 Python Program to iterate strings char by char
"""
def Main():
   string_to_iterate = "Data Science"
   for char in string_to_iterate:
      print(char)

   string_to_iterate = "Data Science"
   for char_index in range(len(string_to_iterate)):
      print(string_to_iterate[char_index])
      
   string_to_iterate = "Python Data Science"
   for char in string_to_iterate[0 : 6 : 1]:
      print(char)
      
   string_to_iterate = "Python_Data_Science"
   for char in string_to_iterate[ :  : 2]:
      print(char)

   string_to_iterate = "Machine Learning"
   for char in string_to_iterate[ :  : -1]:
      print(char)

   string_to_iterate = "Machine Learning"
   char_index = len(string_to_iterate) - 1
   while char_index >= 0:
      print(string_to_iterate[char_index])
      char_index -= 1

   string_to_iterate = "Learn Python"
   char_index = 1
   while char_index <= len(string_to_iterate):
      print(string_to_iterate[-char_index])
      char_index += 1

if __name__ == "__main__":
    Main()

The result of the above coding snippet is as follows:

D
a
t
a
 
S
c
i
e
n
c
e
D
a
t
a
 
S
c
i
e
n
c
e
P
y
t
h
o
n
P
t
o
_
a
a
S
i
n
e
g
n
i
n
r
a
e
L
 
e
n
i
h
c
a
M
g
n
i
n
r
a
e
L
 
e
n
i
h
c
a
M
n
o
h
t
y
P
 
n
r
a
e
L

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Replace all or specified no. of occurrences of chars sub strings in Python Replace All or Some Occurrences of Chars/Sub Strings
Next Article Count frequency of each character in a Python string Compute Frequency in Python String

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x