Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the amount of times a letter appears using python?

I'm trying to count how many times a letter appears in my list. However, whenever I use the count function and input the letter I want to count my return = 0

This is the code:

lab7 =    ['Euclid','Archimedes','Newton','Descartes','Fermat','Turing','Euler','Einstein','Boole','Fibonacci', 'Nash']

print(lab7[1])   #display longest name - a

print(lab7[10])  #display shortest name - b

c = [ word[0] for word in lab7]    
#display str that consists of 1st letter from each name in list - c
print(c)

d = [ word[-1] for word in lab7]
#display str that consists of last letter from each name in list - d
print(d)

**x = input('Enter letter you would like to count here')
lab7.count('x')
e = lab7.count('x')
print(e)**

This is the part of the code that is not working. I keep getting ->

Archimedes
Nash
['E', 'A', 'N', 'D', 'F', 'T', 'E', 'E', 'B', 'F', 'N']
['d', 's', 'n', 's', 't', 'g', 'r', 'n', 'e', 'i', 'h']
Enter letter you would like to count here s
0

As my output.

like image 678
Marisa Avatar asked Jan 18 '26 02:01

Marisa


2 Answers

If you want to count the occurences of a given character among all the words in the list then you may try:

input_char = input('Enter letter you would like to count here')
print "".join(lab7).count(input_char)

If you want the logic to be case-insensetive, the you may convert the input character to lower case using .lower()

You First concatenate all the elements of list to get a unified string and then use the count method to get the occurences of a given character.

like image 114
ZdaR Avatar answered Jan 20 '26 17:01

ZdaR


lst = ['Euclid', 'Archimedes', 'Newton', 'Descartes', 'Fermat',
       'Turing', 'Euler', 'Einstein', 'Boole', 'Fibonacci', 'Nash']

letter = input("Enter the letter you would like to count: ")

count = "".join(lst).lower().count(letter)

print(count)

Which will join all words contained in the list and results in a single string. The string will then be lowered in order to count both uppercase and lowercase letters (e.g. A being equal to a). If uppercase and lowercase letter should not be treated equally, .lower() can be removed.

To check if the input is only a single letter:

lst = ['Euclid', 'Archimedes', 'Newton', 'Descartes', 'Fermat',
       'Turing', 'Euler', 'Einstein', 'Boole', 'Fibonacci', 'Nash']

letter = input("Enter the letter you would like to count: ")

while not letter.isalpha() or len(letter) != 1:
    letter = input("Not a single letter. Try again: ")

print("".join(lst).lower().count(letter))
like image 43
Spherical Cowboy Avatar answered Jan 20 '26 19:01

Spherical Cowboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!