- 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
- Loop Over a String in Python
- Use the for Loop to Loop Over a String in Python
- Use the while Loop to Loop Over a String in Python
- Loop through String in Python
- Use the for loop to loop through String in Python
- Using the range() function
- Using the slicing [] operator
- Using the enumerate() function
- Further reading:
- Use the while loop to loop through String in Python
- Conclusion
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Python Hex to String
- Encode String to UTF-8 in Python
- How To Do Line Continuation in Python
- Convert List to Comma Separated String in Python
- Count Occurrences of Character in String in Python
- Find Character in String in Python
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 LLoop Over a String in Python
- Use the for Loop to Loop Over a String in Python
- Use the while Loop to Loop Over a String in Python
A string is a chain of characters, where every character is at a particular index and can be accessed individually.
In this tutorial, we loop over a string and print individual characters in Python.
Use the for Loop to Loop Over a String in Python
The for loop is used to iterate over structures like lists, strings, etc. Strings are inherently iterable, which means that iteration over a string gives each character as output.
In the above example, we can directly access each character in the string using the iterator i .
Alternatively, we can use the length of the string and access the character based on its index.
Str_value = "String" for index in range ( len ( Str_value ) ): print ( Str_value[index])
The enumerate() function can be used with strings. It is used to keep a count of the number of iterations performed in the loop. It does it by adding a counter to the iterable. It returns an object containing a list of tuples that can be looped over.
for i , j in enumerate("string"): print(i , j)
Use the while Loop to Loop Over a String in Python
The while loop is used just like the for loop for a given set of statements until a given condition is True. We provide the string’s length using the len() function for iterating over a string.
In the while loop, the upper limit is passed as the string’s length, traversed from the beginning.
The loop starts from the 0th index of the string till the last index and prints each character.Str_value = "String" i=0; while(i len(Str_value)): print(Str_value[i]) i=i+1
Loop through String in Python
In this article, we will see how to loop through String in Python.
Iteration or looping means executing a set of statements till a given condition is met. In Python, we can loop over data structures to access their elements. A string is like an array of characters. We can loop through a string and display every character individually.
To achieve this, we can use the for loop and the while loop available in Python.
Use the for loop to loop through String in Python
The for loop is the most basic method to iterate over any sequence. With the help of the for loop, we can execute a set of statements once for every element or character present in a string.
- In the above example, we define the string Hello World .
- Then, we start with the for loop using the variable character that will iterate over every alphabet in the defined string.
- Finally, we print the value in this character variable in every iteration.
We can use different functions within the for loop to make this iteration more convenient. We will discuss these below.
Using the range() function
The range() function generates a sequence of numbers that starts from 0 by default and increments until it encounters the stop value.
We can use it to loop through a string and individually access its characters using their index.
- The len() function returns the length of the string.
- The range() function generates the sequence of numbers from 0 to the length of the string.
- Each number accesses the value at that position in the string.
Using the slicing [] operator
The slicing operator in Python helps in accessing different parts of a sequence or string.
We can use it to loop through a specific part of the string.
We can also use the slicing operator to iterate over a string in the reverse order.
We can do this in the following way.
Using the enumerate() function
The enumerate() function creates an enumerate object by adding a counter to an iterable. We can use this object in the for loop to iterate over the string by accessing its character and counter value at once.
Further reading:
Read File into String in Python
Convert String to List in Python
Use the while loop to loop through String in Python
The while loop is another entry-controlled loop available in Python. Here, we can loop through to the length of the string and access characters using their indexes.
Note that in the while loop, we will have to increment the counter variable individually.
Conclusion
In conclusion, we have seen the use of the for loop and while loop to iterate through a string in Python. We understand that strings are inherently iterable so, it is easier to iterate through them using the for loop. Also, the functions enumerate() and range() , and the slicing operators have been demonstrated in looping through a string.
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Python Hex to String
Table of ContentsUsing bytes.fromhex() MethodUsing binascii ModuleUsing codecs ModuleUsing List Comprehension The representation of data in Hexadecimal is commonly used in computer programming. It is used to represent binary data in a human-readable form, as understanding the machine language (i.e., Binary) is difficult for humans. Hexadecimal notation is used in networking protocols, e.g., IPv6 and […]
Encode String to UTF-8 in Python
Table of ContentsEncode String to UTF-8 in PythonUsing the encode() functionUsing the codecs.encode() functionConclusion The UTF-8 encoding is used by default in Python and represents 8-bit Unicode values. The upgrade to Python 3 saw a major change in using ASCII characters to Unicode characters by default for strings. Encode String to UTF-8 in Python This […]
How To Do Line Continuation in Python
Table of ContentsUsing Backslash (\) OperatorLine Continuation in StringLine Continuation in Number ExpressionUsing Parentheses ()Line Continuation in StringLine Continuation in Number Expression Using Backslash (\) Operator We can use \ operator for line continuation in string and number expression as follows. Line Continuation in String To do line continuation in Python Strings: Use the backslash […]
Convert List to Comma Separated String in Python
Table of ContentsUse .join() MethodUse .join() with map() MethodUse .join() with List Comprehension Use .join() Method To convert a list to a comma separated string in Python, use the .join() method. join() method takes all elements in an iterable and joins them into one string with delimiter as separator. [crayon-64b7c671efbc7036635167/] [crayon-64b7c671efbcb927943591/] First, we created a […]
Count Occurrences of Character in String in Python
Table of ContentsUsing count() MethodUsing Naive for loopUsing List ComprehensionUsing re.findall() MethodUsing for loop with re.finditer() MethodUse the lambda Function with map()Use collections.Counter() Method Using count() Method Use String’s count() method to count occurrences of character in String in Python e.g. my_string.count(character). count() method returns number of occurrences of the character in String. [crayon-64b7c671efd4e648521336/] We […]
Find Character in String in Python
Table of ContentsUsing find() MethodUsing index() MethodUsing for Loop with re.finditer() MethodUsing list comprehension Using find() Method To find the character in a string in Python: Use the find() method to find the index of the first occurrence of the supplied character in the input String. Use an if statement to check if the returned […]