python统计字符串中字母个数
时间: 2023-08-27 15:06:50 浏览: 108
你可以使用 Python 中的 `collections` 模块中的 `Counter` 类来统计字符串中字母的个数。下面是一个例子:
```python
from collections import Counter
string = "Hello, world!"
letter_count = Counter(filter(str.isalpha, string.lower()))
print(letter_count)
```
输出:
```
Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, 'w': 1, 'r': 1, 'd': 1})
```
在上述代码中,我们首先使用 `filter` 函数过滤出所有的字母,并将它们转换为小写。然后,我们使用 `Counter` 类来计算每个字母出现的次数。最后,我们打印出计数器对象 `letter_count` 的内容。
相关问题
python统计字符串中字母出现个数
可以使用Python内置的collections模块中的Counter类来实现字符串中字母出现个数的统计。
示例代码:
```python
from collections import Counter
s = "hello world"
c = Counter(s)
for letter, count in c.items():
if letter.isalpha():
print(f"{letter}: {count}")
```
输出结果:
```
h: 1
e: 1
l: 3
o: 2
w: 1
r: 1
d: 1
```
解释:
1. 首先导入collections模块中的Counter类。
2. 定义字符串s。
3. 使用Counter类统计字符串s中每个字符出现的个数,返回一个字典对象c。
4. 遍历字典c中的每个键值对,判断键是否为字母,如果是则打印出字母和对应的出现次数。
python统计字符串中字母数字字符出现的次数
可以使用Python内置的字符串函数count()来统计字符串中字母数字字符出现的次数。
示例代码如下:
```python
s = 'Hello123'
count_alpha = sum(c.isalpha() for c in s)
count_digit = sum(c.isdigit() for c in s)
print("字母字符出现的次数:", count_alpha)
print("数字字符出现的次数:", count_digit)
```
输出结果为:
```
字母字符出现的次数: 5
数字字符出现的次数: 3
```
其中,sum()函数用于将True和False转化为1和0,从而实现统计出现次数的功能。isalpha()和isdigit()函数分别用于判断字符是否为字母和数字字符。
阅读全文
相关推荐














