我希望我的代码仅按字母顺序输出字符串中的每个字母一次,例如banana将输出abn.
问题是我仍然需要它来计算字符串中每个字母的出现次数,所以输出应该如下:
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)
...
这是我的代码:
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')
而当前的输出如下:
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
呼唤远方
梦里花落0921
相关分类