用python统计字符出现的次数。编写程序,对输入的字符串中各字符出现的次数进行统计
时间: 2023-06-05 10:06:57 浏览: 780
好的,这个问题可以回答。下面是用 Python 统计字符出现次数的程序:
```python
string = input("请输入字符串:")
count = {}
for s in string:
if s in count:
count[s] += 1
else:
count[s] = 1
for s in count:
print("字符 '%s' 出现了 %d 次。" % (s, count[s]))
```
输入一个字符串,程序会输出字符串中各字符出现的次数。例如输入 "hello",输出如下:
```
字符 'h' 出现了 1 次。
字符 'e' 出现了 1 次。
字符 'l' 出现了 2 次。
字符 'o' 出现了 1 次。
```
相关问题
编写python程序,统计字符串中,某个字符串出现的次数
好的,以下是一个简单的Python程序,用于统计一个字符串中某个特定字符串的出现次数:
```
def count_substring(string, sub):
count = 0
for i in range(len(string)):
if string[i:i+len(sub)] == sub:
count += 1
return count
string = input("请输入字符串:")
sub = input("请输入要统计的子字符串:")
count = count_substring(string, sub)
print(sub + "在" + string + "中出现的次数为:" + str(count))
```
你可以将要统计的字符串作为程序的输入,然后输入你想要统计的子字符串。程序将返回你要求的结果,即该子字符串在输入的字符串中出现的次数。
Python对用户输入的字符串中各字母出现的次数进行统计,统计结果用字典存放
可以使用Python中的字典来实现对字符串中各字母出现次数的统计,具体代码如下:
```python
str_input = input("请输入一个字符串:")
char_count = {} # 字典用来存放统计结果
for char in str_input:
if char not in char_count: # 如果字典中没有该字符,就加入字典并初始化计数为0
char_count[char] = 0
char_count[char] += 1 # 统计该字符出现的次数
print("输入的字符串中各字母出现的次数为:")
for char, count in char_count.items():
print(char, ":", count)
```
以上代码首先获取用户输入的字符串,然后使用一个空字典char_count来存放统计结果。接着使用for循环遍历字符串中的每个字符,如果该字符不在字典char_count中,就将该字符加入字典并初始化计数为0,然后统计该字符出现的次数。最后使用for循环遍历字典char_count中的每个键值对,输出每个字符及其出现的次数。