- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate over characters of a string in Python
In this article, we will learn about iterating/ traversing over characters of a string in Python 3.x. Or earlier.
The string is a collection of characters which may contain spaces, alphabets or integers. They can be accessed using indexes or via references . Some commonly implemented methods are shown below.
Method 1 − The direct itertor without indexing
Example
string_inp = "tutorialspoint" # Iterate over the string for value in string_inp: print(value, end='')
Method 2 − The most common way using index based access
Example
string_inp = "tutorialspoint" # Iterate over the string for value in range(0,len(string_inp)): print(string_inp[value], end='')
Method 3 − The enumerate type
Example
string_inp = "tutorialspoint" # Iterate over the string for value,char in enumerate(string_inp): print(char, end='')
Method 4 − Access using negative indexes
Example
string_inp = "tutorialspoint" # Iterate over the string for value in range(-len(string_inp),0): print(string_inp[value], end='')
Method 5 − Access via slicing methods
Example
string_inp = "tutorialspoint" # Iterate over the string for value in range(0,len(string_inp)): print(string_inp[value-1:value], end='') print(string_inp[-1:])
The ouptut produced by all 5 methods are identical and displayed below.
Output
tutorialspoint
Conclusion
In this article, we learnt about iteration/traversal over elements of a list. We also learnt about various ways of traversal.
Advertisements