Iterate over each character in a Python string
This post will discuss how to iterate over each character in a string in Python.
1. Using for-loop
A simple solution is to use the loop construct to print characters in the string.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" for c in s: print(c) |
2. Using enumerate() function
The Pythonic solution to iterate over each character in a string along with an index is using the built-in function enumerate().
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" for i, c in enumerate(s): print((i, c)) |
3. Using range() function
Another option to iterate over the string with indexes can be done using the range() and len().
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" for i in range(len(s)): print((i, s[i])) |
That’s all about iterating over each character in a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)