Dakota Brown
Dakota Brown

Reputation: 57

How to count the number of times a specific character appears in a list?

Okay so here is a list:

sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']

I want to be able to count the total number of times a user inputted letter appears throughout the entire list.

userLetter = input('Enter a letter: ')

Let's say the letter is 'a'

I want the program to go through and count the number of times 'a' appears in the list. In this case, the total number of 'a' in the list should be 8.

I've tried using the count function through a for loop but I keep getting numbers that I don't know how to explain, and without really knowing how to format the loop, or if I need it at all.

I tried this, but it doesn't work.

count = sentList.count(userLetter)

Any help would be appreciated, I couldn't find any documentation for counting all occurrences of a letter in a list.

Upvotes: 0

Views: 13960

Answers (6)

Nadia Sharief
Nadia Sharief

Reputation: 1

example program to check if entered letter is present in random choice of word

word_list = ["aardvark", "baboon", "camel"]

import random

chosen_word = random.choice(word_list)

guess = input("Guess a letter: ").lower()

for letter in chosen_word:

    if letter == guess:

        print("Right")
    else:

        print("Wrong")

Upvotes: 0

Nadia Sharief
Nadia Sharief

Reputation: 1

word_list = ["aardvark", "baboon", "camel"] import random chosen_word = random.choice(word_list) guess = input("Guess a letter: ").lower()

for letter in chosen_word: if letter == guess: print("Right") else: print("Wrong")

Upvotes: 0

Ankush Bhatia
Ankush Bhatia

Reputation: 153

Merge all the strings into a single string and then use the count function.

count = ''.join(sentList).count(userLetter)

Upvotes: 2

Joe Davy
Joe Davy

Reputation: 783

Have you tried something like this?

userLetter = input('Enter a letter: ')
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']

letterCount = 0
for sentence in sentList:
    letterCount += sentence.count(userLetter)

print("Letter appears {} times".format(letterCount))

Upvotes: 0

aghast
aghast

Reputation: 15310

Use the sum() builtin to add up the counts for each string in the list:

total = sum(s.count(userLetter) for s in sentList)

Upvotes: 4

Kaushik NP
Kaushik NP

Reputation: 6781

Your approach is halfway correct. The problem is that you need to go through the list.

word_count=0
for l in sentList:
     word_count+= l.count(userLetter)

Upvotes: 0

Related Questions