
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
- Related Questions & Answers
- Iterate over a dictionary in Python
- Iterate over a list in Python
- Iterate over a set in Python
- How to iterate individual characters in a Lua string?
- C# program to iterate over a string array with for loop
- Python program to iterate over multiple lists simultaneously?
- How to iterate over a Java list?
- How to iterate over a C# dictionary?
- How to iterate over a C# list?
- How to iterate over a C# tuple?
- Java Program to Iterate over a HashMap
- Java Program to Iterate over a Set
- Iterate over the elements of HashSet in Java
- Iterate over lines from multiple input streams in Python
- How to iterate over a Hashmap in Kotlin?
Advertisements