Iterate over characters of a string in Python

PythonServer Side ProgrammingProgramming

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.

raja
Published on 07-Aug-2019 11:40:14
Advertisements