How Can We Help?
In Python, it’s a common task to iterate through a string to get character by character or split it into multiple chunks, or even loop over that string in reverse order.
How to iterate through a string in Python? To iterate over a string in Python, we use loops like (for loop or while loop). We also can use RANGE with for loop to iterate through a range of characters in a string. Another way we use INDEX is to return each character of a particular index. We also can split the string into chunks of a specified number of characters.
This article will explain iterating over string in Python by giving multiple practical examples for better understanding.
Syntax:
for iterating_element in (string_value/string_variable_name) :
(for block)
Input Parameters:
- iterating_element: the variable that will hold each value of a given string.
- string_value/string_variable_name: The strings that we want to iterate through it.
Python Iterate String Using for loop
Example (1)
mystring = "Hello python";
for ch in mystring:
print("Index of Element :", mystring.index(ch) , " - Element of string:",ch)
Output:
('Index of Element :', 0, ' - Element of string:', 'H')
('Index of Element :', 1, ' - Element of string:', 'e')
('Index of Element :', 2, ' - Element of string:', 'l')
('Index of Element :', 2, ' - Element of string:', 'l')
('Index of Element :', 4, ' - Element of string:', 'o')
('Index of Element :', 5, ' - Element of string:', ' ')
('Index of Element :', 6, ' - Element of string:', 'p')
('Index of Element :', 7, ' - Element of string:', 'y')
('Index of Element :', 8, ' - Element of string:', 't')
('Index of Element :', 9, ' - Element of string:', 'h')
('Index of Element :', 4, ' - Element of string:', 'o')
('Index of Element :', 11, ' - Element of string:', 'n')
In the above example, we fetched the string value ‘python’ element and printed it in separate lines using iteration.
Python Iterate String with index Using for loop and range()
Example (2)
mystring = "Hello Python"
# getting length of string
lengthOfmystring = len(mystring)
# Iterating the index
for var in range(lengthOfmystring):
print("Element of string:" , mystring[var])
Output:
('Element of string:', 'H')
('Element of string:', 'e')
('Element of string:', 'l')
('Element of string:', 'l')
('Element of string:', 'o')
('Element of string:', ' ')
('Element of string:', 'P')
('Element of string:', 'y')
('Element of string:', 't')
('Element of string:', 'h')
('Element of string:', 'o')
('Element of string:', 'n')
In the above example, using for loops with rang, we iterate through the range of our string “mystring” and then print each string value in a separate line.
Python Iterate String with Index Using while loop and range()
Example (3)
mystring = "Hello Oraask"
# Getting length of string
lengthOfmystring = len(mystring)
i = 0
# Iterating through the string using while loop
while i < lengthOfmystring:
print("Element of string:" , mystring[i])
i += 1
Output:
('Element of string:', 'H')
('Element of string:', 'e')
('Element of string:', 'l')
('Element of string:', 'l')
('Element of string:', 'o')
('Element of string:', ' ')
('Element of string:', 'O')
('Element of string:', 'r')
('Element of string:', 'a')
('Element of string:', 'a')
('Element of string:', 's')
('Element of string:', 'k')
In the above example, using iteration with a while loop, we fetched the element of string (“Hello Oraask”) and printed them together in separate lines.
Python Iterate Through Characters of a String
Using string[start position: stop position: incremental step], we can iterate through a portion of our string variable by creating a small string slice by using the [] string slicing operator.
Example (4)
mystring = "Hello Oraask"
# Iterating through the string using while loop
for i in mystring[6:12:1] :
# Print all characters iterated
print("Element of string:" , i)
Output:
('Element of string:', 'O')
('Element of string:', 'r')
('Element of string:', 'a')
('Element of string:', 'a')
('Element of string:', 's')
('Element of string:', 'k')
In the above example, using iteration with the slicing operator, we have fetched the elements from position 6 to position 12 of a string (“Hello Oraask”) which is a word (“Oraask”), and then print them together in separate lines.
Python Iterate String Backwards
Using string[start position (-): stop position (-): incremental step (-)], we can iterate through a portion of our string variable backward by creating a small slice of our string by using the [] string slicing operator.
Example (5)
mystring = "Hi Python"
# Iterating through the string using while loop
for i in mystring[-1: -7 : -1] :
# Print all characters iterated
print("Element of string:" , i)
Output:
('Element of string:', 'n')
('Element of string:', 'o')
('Element of string:', 'h')
('Element of string:', 't')
('Element of string:', 'y')
('Element of string:', 'P')
In the above example, using iteration with a slicing operator but with a negative sign for starting, end, and incremental positions, we have fetched the elements from position -1 to position -7 of a string (“Hi Python”) which is a word (“nohtyp”) and then print them together in separate lines.
Python Iterate string 2 characters at a time
Using string[start position: stop position: incremental step ], we can iterate over a string variable but skip two characters simultaneously.
Example (6)
mystring = "Hello Oraask"
# Getting length of string
lengthOfmystring = len(mystring)
# Iterating through the string using while loop
for i in mystring[0:lengthOfmystring:2] :
# Print all characters iterated
print("Element of string:" , i)
Output:
('Element of string:', 'H')
('Element of string:', 'l')
('Element of string:', 'o')
('Element of string:', 'O')
('Element of string:', 'a')
('Element of string:', 's')
In the above example, using incremental position to indicate how the iterator behaves like iterate string two characters at a time, we have jumped two characters at a time over our string which is (“HloOas”) by riding characters (“el rak”), and then print them together in separate lines.
Python Iterate string in chunks
Using list Comprehension with the string, we can split the string into chunks of a specific length and then return the result as an array.
Example (7)
mystring = "backballbillbothbulkcastcarecase"
# Getting length of string
chunksplit = 4
chunks = [mystring[i:i+chunksplit]
# Iterating through the string using rang
for i in range(0, len(mystring), chunksplit)]
# Print the new list consists of words of 4 character each
print(chunks)
Output:
['back', 'ball', 'bill', 'both', 'bulk', 'cast', 'care', 'case']
In the above example, we have created a new list called chunks to hold the new values as chunks of 4 characters, each of the “mystring” variables. You can change the “checksplit” variable value to indicate how many characters should be split into chunks.
How to Iterate Through Alphabet in Python
We can iterate through the alphabet in python using a simple for loop first, we have to create the alphabet variable to be able to iterate through it.
Example (8)
#Import string module
import string
# Create alphabet variable
alphabetsVar = string.ascii_lowercase
# Loop over alphabets
for i in alphabets:
print i
Output:
a b c d e f g h i j k l m n o p q r s t u v w x y z
Explanation:
In the above example, we imported the string module, then, using the string, we created the alphabetsVar variable; then, using normal for loop, we iterated over the alphabet and printed it.
In this tutorial, you have learned how to iterate through string elements in python using for loop, for loop with rang and while loop with rang.
If you have an inquiry or doubt don’t hesitate to leave them in comment. we are waiting your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Similar Python operators:
- Concatenation(‘+’) : It adds two strings.
- Membership(‘in’ & ‘not in’) : It returns True , if given element is present in string otherwise returns False.
- Repetition(‘*’) : It repeats element of string.
Related Articles
Python String – Mastering By Practical Examples (Comprehensive Guide)
Python Tutorials List:
- Python tutorials list: access all python tutorials.