计算python中字符串字母的出现次数

Tan*_*ary -1 python count

包含大写和小写字母的字符串。

我们需要计算每个字母的出现次数(不区分大小写)并显示相同。

下面是程序,但没有导致所需的输出

输出应该是- 2A 3B 2C 1G

我的输出是 - A 2 B 3 A 2 B 3 C 2 B 3 G 1 C 2

String="ABaBCbGc"
String1=String.upper()
for i in String1:
    print(i,String1.count(i))
Run Code Online (Sandbox Code Playgroud)

Dan*_*ejo 5

使用计数器

from collections import Counter

String = "ABaBCbGc"

counts = Counter(String.lower())

print(counts)
Run Code Online (Sandbox Code Playgroud)

输出

Counter({'b': 3, 'c': 2, 'a': 2, 'g': 1})
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢大写,只需更改str.lowerstr.upper. 或者使用字典来跟踪计数:

string = "ABaBCbGc"
counts = {}
for c in string.upper():
    counts[c] = counts.get(c, 0) + 1

print(counts)
Run Code Online (Sandbox Code Playgroud)

输出

{'C': 2, 'B': 3, 'A': 2, 'G': 1}
Run Code Online (Sandbox Code Playgroud)