Reputation: 11
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
Reputation: 1
def print_count(pr):
for item in pr:
print(item, pr.count(item))
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
Reputation: 67968
x = "testert"
print(x.count("e"))
print(x.count("t"))
You can do it easily using this.
Output:
2
3
Upvotes: 3