user3559135
user3559135

Reputation: 11

How count the number of times a letter appears in word using python

Is there a better way to write out this python code- to count the number times a letter appears in a word.For instance 'idiosyncrasy' has two letter 'y' in the word.How do I count and output the number of times a letter appears in a word. Just trying to keep it simple with for loops and while statements.Still a python newbie.

Sample Code:

def display():
    letter = str(input('enter a letter: '))
    word = str(input('enter a word: '))
    print(countNum(word,letter))

def countNum(letter, word):
    count = 0
    index = 0
    for letter in word:
        if str(word[index]) == letter :  
           print(count)
           count = count + 1

Upvotes: 1

Views: 10775

Answers (2)

Katya
Katya

Reputation: 1

  1. The simplest way:
def print_count(pr):
    for item in pr:
        print(item, pr.count(item))
  1. If you want for each letter to be printed only 1 time and with keeping sequence:
def unique(sequence):
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]

def print_count(pr):
    for item in unique(pr):  
        print(item, pr.count(item))

Upvotes: 0

vks
vks

Reputation: 67968

x = "testert"
print(x.count("e"))
print(x.count("t"))

You can do it easily using this.

Output:

2
3

Upvotes: 3

Related Questions