I want my code to output each letter in the string only once and in alphabetical order, for example banana
will output abn
.
The catch is that I still need it to count the occurrences of each letter in the string, so the output should be as follows:
a occurs in the word banana a total of 3 times(s)
b occurs in the word banana a total of 1 time(s)
n occurs in the word banana a total of 2 time(s)
...
This is my code:
def letter_counter(string):
stg = string.lower()
stg = ''.join(sorted(stg))
for i in stg:
a = stg.count(i)
print(f'the letter {i} appears in the word {string} {a} times')
letter_counter('banana')
And the current output is as follows:
the letter a appears in the word banana 3 times
the letter a appears in the word banana 3 times
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 times
the letter n appears in the word banana 2 times
the letter n appears in the word banana 2 times
You can use a Counter
to easily count the letters for you:
from collections import Counter
def letter_counter(string):
for letter, count in sorted(Counter(string.lower()).items()):
print(f'the letter {letter} appears in the word {string} {count} times')
letter_counter("banana")
Gives:
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 times
the letter n appears in the word banana 2 times
For unique letters you can try to use set(). So something like for i in sorted(set(stg)):
The trick to remove duplicates is to make it a set
:
def letter_counter(string):
stg = string.lower()
stg = ''.join(stg)
for i in sorted(set(stg)):
a = stg.count(i)
print(f'the letter {i} appears in the word {string} {a} time{"" if a == 1 else "s"}')
letter_counter('banana')
prints out:
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 time
the letter n appears in the word banana 2 times
Note the move from sorted
one line later. A set
is unordered so the original sorted order is lost. Sorting it again, just before looping, sorts this out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.