python统计几种字符个数
时间: 2023-10-18 20:09:16 浏览: 77
Python可以通过以下代码统计字符串中每种字符出现的次数:
```python
s = input("请输入一个字符串:")
d = {}
for char in s:
if char in d:
d[char] += 1
else:
d[char] = 1
for key, value in d.items():
print("{}: {}".format(key, value))
```
你可以输入任何一个字符串,这段代码都会输出字符串中每个字符出现的次数。
相关问题
python如何统计字符个数
在Python中,统计字符个数的方法有很多,以下是几种常见的方法:
1. **使用`len()`函数**:
`len()`函数可以直接返回字符串的长度,即字符的个数。
```python
text = "Hello, World!"
count = len(text)
print(count) # 输出: 13
```
2. **使用`collections.Counter`**:
`collections.Counter`可以统计每个字符出现的次数。
```python
from collections import Counter
text = "Hello, World!"
counter = Counter(text)
print(counter) # 输出: Counter({'l': 3, 'o': 2, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1, 'H': 1, 'e': 1})
```
3. **使用字典**:
可以手动创建一个字典来统计每个字符出现的次数。
```python
text = "Hello, World!"
char_count = {}
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count) # 输出: {'H': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}
```
4. **使用`for`循环和`count()`方法**:
可以使用`for`循环和字符串的`count()`方法来统计每个字符出现的次数。
```python
text = "Hello, World!"
char_count = {}
for char in text:
char_count[char] = text.count(char)
print(char_count) # 输出: {'H': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}
```
这些方法各有优缺点,可以根据具体需求选择合适的方法。
统计几种字符个数 Description 输入一行字符,分别统计英文字母、空格、数字和其他字符的4种个数。 Format Input 输入一行字符,包含英文字母、空格、数字和其他字符。 Output 输出字符统计的个数,每行1种。 Samples 输入数据 1 Python 3.6.0中文版 输出数据 1 6 1 3 5
以下是 Python 3 代码实现:
```python
s = input() # 输入一行字符
letter_count = 0 # 英文字母个数
space_count = 0 # 空格个数
digit_count = 0 # 数字个数
other_count = 0 # 其他字符个数
for c in s:
if c.isalpha(): # 判断是否是英文字母
letter_count += 1
elif c.isspace(): # 判断是否是空格
space_count += 1
elif c.isdigit(): # 判断是否是数字
digit_count += 1
else: # 其他字符
other_count += 1
print(letter_count)
print(space_count)
print(digit_count)
print(other_count)
```
输入样例:
```
Python 3.6.0中文版
```
输出样例:
```
6
1
3
5
```
阅读全文
相关推荐













