键盘录入一个字符串,请统计每种字符出现的次数
时间: 2023-11-10 07:05:27 浏览: 62
```python
# 方法1:使用字典来统计每个字符出现的次数
s = input('请输入字符串:')
d = {}
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
print('每种字符出现的次数为:')
for k, v in d.items():
print(k, ':', v)
# 方法2:使用collections模块中的Counter类来统计每个字符出现的次数
from collections import Counter
s = input('请输入字符串:')
c = Counter(s)
print('每种字符出现的次数为:')
for k, v in c.items():
print(k, ':', v)
```
示例输出:
```
请输入字符串:hello world
每种字符出现的次数为:
h : 1
e : 1
l : 3
o : 2
: 1
w : 1
r : 1
d : 1
请输入字符串:abcbca
每种字符出现的次数为:
a : 2
b : 2
c : 2
```
相关问题
键盘录入一个字符串,统计每种字符出现的次数,最终在控制台输出一个字符串
输入示例:hello world!
输出示例:
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
!: 1
字符串统计结果为:h1e1l3o2 1w1r1d1!1
代码如下:
```python
str_input = input("请输入一个字符串:") # 键盘录入一个字符串
# 统计每种字符出现的次数
count_dict = {} # 定义一个字典,用于存储每种字符出现的次数
for char in str_input:
if char in count_dict:
count_dict[char] += 1
else:
count_dict[char] = 1
# 输出每种字符出现的次数
for char, count in count_dict.items():
print(f"{char}: {count}")
# 组合成统计结果字符串
result_str = ""
for char, count in count_dict.items():
result_str += char + str(count)
print(f"\n字符串统计结果为:{result_str}")
```
键盘录入一个字符串, 请统计字符串中每个字符出现的次数?
好的,以下是Python的实现代码:
```python
str_input = input("请输入一个字符串:") # 键盘录入一个字符串
char_dict = {} # 定义一个空字典
# 遍历字符串中每个字符,统计出现次数
for char in str_input:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
# 输出每个字符出现的次数
for key, value in char_dict.items():
print(f"{key}: {value}次")
```
运行示例:
```
请输入一个字符串:hello world
h: 1次
e: 1次
l: 3次
o: 2次
: 1次
w: 1次
r: 1次
d: 1次
```