Looping and counting in string
Iteration through the characters of a string.
The function count takes a string as its parameter.
The for statement iterates through each character in the string and checks if the character is equal to the value of Char. If so, the counting variable, count, is incremented by one. When all characters have been processed, the count is returned.
Example:- program counts the number of times the letter a appears in a string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print (count)output:-
output:-
0
1
1
2
2
3
Example:-
def count(text, Char):
count = 0
for c in text:
if c == Char:
count = count + 1
return count
print(count("banana","a"))
output:-
3
USE enumerate ()
TO TRACK THE NUMBER OF ITERATIONS WITHIN A FOR-LOOP
for iteration, item in enumerate (iterable)
with iterable
as any iterable object.
For each iteration, iteration
will be the current number of iterations performed and item
will be the current item in iterable
.
Example:-
a_list
=
["a",
"b",
"c",
"d"]
for iteration
, item
in
enumerate(a_list
):
print(iteration
)
OUTPUT
0
1
2
3
===================*********************************=================
0 Comments