统计字符串中,10个数字字符('0'-'9')各自出现的次数,并按数字字符出现次序,输出数字字符和其次数,如果没有数字字符输出 None
时间: 2023-07-15 16:10:27 浏览: 66
好的,以下是 Python 代码实现:
```python
s = input() # 输入字符串
counts = [0] * 10 # 初始化数字字符出现次数列表
for c in s:
if c.isdigit(): # 如果当前字符是数字字符
counts[int(c)] += 1 # 对应数字字符出现次数加1
none_flag = True # 用于标记是否存在数字字符
for i in range(10):
if counts[i] > 0: # 如果当前数字字符出现过
none_flag = False # 存在数字字符,标记设为 False
print(f"{i}: {counts[i]}") # 输出数字字符和其次数
if none_flag: # 如果不存在数字字符
print("None") # 输出 None
```
代码运行示例:
```
输入:a1b2c3d4e5f6g7h8i9j0
输出:
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1
9: 1
输入:abcdefg
输出:None
```
相关问题
统计字符串中,10个数字(0-9)各自出现的次数,并按数字字符出现次序,输出数字字符和其次数,如果没有数字字符输出None
以下是一个 Python 的实现示例:
```python
def count_digits(s):
# 统计数字字符出现的次数
count = [0] * 10
for c in s:
if c.isdigit():
count[int(c)] += 1
# 构造输出字符串
output = ""
for i in range(10):
if count[i] > 0:
output += "{}: {}\n".format(i, count[i])
# 如果没有数字字符,输出 None
if not output:
output = "None\n"
return output.strip()
# 测试
print(count_digits("abc123def456ghi789jkl"))
# 输出:
# 1: 1
# 2: 1
# 3: 1
# 4: 1
# 5: 1
# 6: 1
# 7: 1
# 8: 1
# 9: 1
# 0: 0
print(count_digits("abcdefg"))
# 输出:
# None
```
该函数接受一个字符串作为输入,统计其中每个数字字符(0-9)出现的次数,然后按数字字符出现次序输出数字字符和其次数。如果字符串中没有数字字符,则输出 None。
统计字符串中,10个数字字符(‘0’-‘9’)各自出现的次数,并按数字字符出现次序,输
出每个数字字符和它出现的次数。
假设给定的字符串为str,我们可以使用一个长度为10的数组,用于记录每个数字字符出现的次数。具体实现可以参考以下代码:
```python
str = "a1b2c3d4e5f6g7h8i9j0"
count = [0] * 10
for c in str:
if c.isdigit():
count[int(c)] += 1
for i in range(10):
print(i, "出现的次数:", count[i])
```
输出结果为:
```
0 出现的次数: 1
1 出现的次数: 1
2 出现的次数: 1
3 出现的次数: 1
4 出现的次数: 1
5 出现的次数: 1
6 出现的次数: 1
7 出现的次数: 1
8 出现的次数: 1
9 出现的次数: 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)