- How to Iterate over a String in Python
- Multiple Ways to Iterate Strings in Python
- Using for loop to traverse a string
- Python range to iterate over a string
- How to use the slice operator to iterate strings partially
- Traverse string backward using the slice operator
- Using indexing to iterate strings backward
- Summary – Program to iterate strings char by char
- Python Strings
- Example
- Assign String to a Variable
- Example
- Multiline Strings
- Example
- Example
- Strings are Arrays
- Example
- Looping Through a String
- Example
- String Length
- Example
- Check String
- Example
- Example
- Check if NOT
- Example
- Example
How to Iterate over a String in Python
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.
Multiple Ways to Iterate Strings in Python
The following are various ways to iterate the chars in a Python string. Let’s first begin with the for loop method.
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:
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.
""" 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:
How to use the 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.
# 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:
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:
Traverse 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
Using 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 use the indexing to iterate strings 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_indexThe result of the above coding snippet is as follows:
Summary – Program to iterate 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_indexThe 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 LPython Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello" .
You can display a string literal with the print() function:
Example
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)Note: in the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
Learn more about For Loops in our Python For Loops chapter.
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in .
Example
Check if "free" is present in the following text:
Use it in an if statement:
Example
Print only if "free" is present:
Learn more about If statements in our Python If. Else chapter.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in .
Example
Check if "expensive" is NOT present in the following text:
Use it in an if statement:
Example
print only if "expensive" is NOT present: