ByteBoard Notes Notes

To print the number of occurrences of a given letter in each string of a list

Informatics Practices XI · Experiment 14 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.14
Page No.28

Occurrences of a letter

Aim

To write a Python program that inputs several strings into a list and prints how many times a given letter occurs in each string.

Concepts used

Algorithm

  1. Input how many strings and append each to a list.
  2. Input the letter.
  3. For each string, use count() to find how many times the letter occurs and print it.

Program

# Occurrences of a letter in each string of a list strings = []n = int(input("How many strings? "))for i in range(n):    strings.append(input("Enter a string: "))letter = input("Enter the letter: ")for s in strings:    print(s, ":", s.count(letter))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python occurrences_of_letter.py
How many strings? 3 Enter a string: banana Enter a string: apple Enter a string: grape Enter the letter: a banana : 3 apple : 1 grape : 1

✓ Printed by running this program, not typed by hand.

Result

The letter a occurs 3 times in "banana", once in "apple" and once in "grape".

Viva voce: what the examiner may ask

01What does the string method count() return?

How many times the given substring occurs in the string.

02Is count() case-sensitive?

Yes. "Apple".count("a") is 0.

03Can a list hold strings?

Yes. A list can hold values of any type.

Variations for the lab test

  1. Make the count case-insensitive with lower().
  2. Display only the strings in which the letter does not occur.
  3. Display the string with the most occurrences.
! Common mistake Using strings.count(letter) counts list items equal to "a", which gives 0 here.
Back to the 11-IP index