String Traversal and the for loop
- Computations are used to processing a string one character at a time.
- It starts at the beginning, select each character in turn and continue until the end. This pattern of processing is called a traversal.
- The for statement can iterate over the items of a sequence. A string is simply a sequence of characters and the for loop iterates over each character automatically. This sequence iteration called as iteration by item. It process the characters one at a time from left to right.
Example:-
for i in ["a", "b", "c", "d", "e"]:
i = "Hi " + i
print(i)
Output: -
Hi a
Hi b
Hi c
Hi d
Hi e
Example:-
s = "py thon"
for ch in s:
print("HELLO")
output:-
HELLO
HELLO
HELLO
HELLO
HELLO
HELLO
HELLO
Multiple Ways to Iterate Strings by for loop in Python
1. Using for loop to traverse a string
2. Range to iterate over a string
3. Slice operator to iterate strings partially
4. Using enumerate()
function
1. Using for loop to traverse a string
It is the most prominent and straightforward technique to iterate strings.
Example:-
string_to_iterate = "Data Science"
for char in string_to_iterate:
print(char)
Output: -
D
a
t
a
S
c
i
e
n
c
e
2. Range to iterate over a string
This method lets us access string elements using the index.
Example:-
string_to_iterate = "Data Science"
for char_index in range(len(string_to_iterate)):
print(string_to_iterate[char_index])
Output:-
D
a
t
a
S
c
i
e
n
c
e
3. Slice operator to iterate strings partially
Traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially.
The [] operator has the following syntax:
string [starting index : ending index : step value]
Example:-
string_to_iterate = "Python Data Science"
for char in string_to_iterate[0 : 6 : 1]:
print(char)
Output:-
P
y
t
h
o
n
By slice operator using iterate over a string but leaving every alternate character.
Example:-
string_to_iterate = "Python_Data_Science"
for char in string_to_iterate[ : : 2]:
print(char)
Output:-
P
t
o
_
a
a
S
i
n
e
Traverse string backward using slice operator
Pass a -ve step value and skipping the starting as well as ending indices, then you can iterate in the backward direction.
Example:-
string_to_iterate = "Machine Learning"
for char in string_to_iterate[ : : -1]:
print(char)
output:-
g
n
i
n
r
a
e
L
e
n
i
h
c
a
M
4. Using enumerate()
function
Check Boolean values
Example:-
str = "abcdef"
for i, v in enumerate(str):
print(v)
Output:-
a
b
c
d
e
f
==================================================================
0 Comments