Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Iterate over characters of a string in Python
In this article, we will learn about iterating over characters of a string in Python. A string is a collection of characters that can include spaces, alphabets, or integers, and we can access them using various iteration methods.
Using Direct Iteration
The simplest way to iterate over a string is to use a for loop directly ?
text = "tutorialspoint"
# Iterate over the string
for char in text:
print(char, end='')
tutorialspoint
Using Index-Based Access
Access characters using their index positions with range() ?
text = "tutorialspoint"
# Iterate using index
for i in range(len(text)):
print(text[i], end='')
tutorialspoint
Using enumerate()
Get both index and character simultaneously using enumerate() ?
text = "tutorialspoint"
# Iterate with index and character
for index, char in enumerate(text):
print(f"{index}: {char}")
0: t 1: u 2: t 3: o 4: r 5: i 6: a 7: l 8: s 9: p 10: o 11: i 12: n 13: t
Using Negative Indexing
Access characters from the end using negative indices ?
text = "tutorialspoint"
# Iterate using negative indexing
for i in range(-len(text), 0):
print(text[i], end='')
tutorialspoint
Using String Slicing
Extract individual characters using slice notation ?
text = "tutorialspoint"
# Iterate using slicing
for i in range(len(text)):
print(text[i:i+1], end='')
tutorialspoint
Comparison
| Method | Provides Index? | Best For |
|---|---|---|
| Direct iteration | No | Simple character processing |
| Index-based | Yes | When index is needed |
| enumerate() | Yes | When both index and character needed |
| Negative indexing | Yes | Reverse order processing |
Conclusion
Use direct iteration for simple character processing. Use enumerate() when you need both index and character, and index-based access when you need more control over positioning.
