使用Python统计一个指定字符串中每个字符出现的次数
时间: 2024-01-09 09:04:10 浏览: 29
有多种方法可以统计一个指定字符串中每个字符出现的次数,下面列出其中两种常用的方法:
方法一:使用字典
```python
s = 'hello, world!'
d = {}
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
print(d)
```
输出:
```
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}
```
方法二:使用collections模块的Counter类
```python
from collections import Counter
s = 'hello, world!'
c = Counter(s)
print(c)
```
输出:
```
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
```
以上两种方法得到的结果是一样的,即一个字典或Counter对象,其中键为字符,值为出现次数。
相关问题
python 统计一个指定字符串中每个字符出现的次数
可以使用Python内置函数`collections.Counter()`来统计一个指定字符串中每个字符出现的次数。具体实现如下:
```python
from collections import Counter
string = "hello world"
result = Counter(string)
print(result)
```
输出结果为:
```
Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
```
其中,`Counter()`函数返回一个字典,键为出现的字符,值为该字符出现的次数。```{'l': 3, 'o': 2, 'e': 1, 'h': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}```表示字符'l'出现了3次,字符'o'出现了2次,以此类推。
用python统计一个指定字符串中每个字符出现的次数
可以使用Python中的字典来统计一个指定字符串中每个字符出现的次数。以下是示例代码:
```python
s = 'hello, world!'
counts = {}
for c in s:
if c in counts:
counts[c] += 1
else:
counts[c] = 1
print(counts)
```
输出结果为:
```
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}
```
其中,字典counts的键是字符串中出现的字符,值是该字符在字符串中出现的次数。