Thursday, February 9, 2017

Using Loops to Count Specific Characters In a String

The following program counts the number of times the letter l appears in a string:
s = 'I will be back'
count=0
for letter in s:
    if letter == 'l':
        count = count + 1
print count
2

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an l is found. When the loop exits, count contains the result-the total number of l’s.
Now we can create function called counts in order to count the specific letters/characters in a string.
def counts(x):
    count = 0
    s = str(x)
    l = raw_input('Enter a letter or a string: ')
    for letter in s:
        if letter == l:
            count = count + 1
    print count
x='This is my life'
counts(x)



No comments:

Post a Comment