统计字符串中,10个数字字符(‘0’-‘9’)各自出现的次数,并按数字字符出现次序,输出数字字符和其次数,如果没有数字字符输出None
时间: 2023-07-15 18:10:27 浏览: 30
一个字符串中出现次数最多的字符 统计这个次数【实现代码】
可以使用一个长度为10的数组来统计每个数字字符出现的次数。遍历字符串,如果当前字符是数字字符,则将对应数字的计数器加1。最后遍历计数器数组,输出每个数字字符和其出现次数即可。
以下是示例代码实现:
```python
def count_digits(s):
if not any(c.isdigit() for c in s):
return "None"
counter = [0] * 10
for c in s:
if c.isdigit():
counter[int(c)] += 1
result = ""
for i, count in enumerate(counter):
if count > 0:
result += f"{i}: {count}\n"
return result.strip()
```
示例输入:
```python
s = "a1b2c3d4e5f6g7h8i9j0k"
print(count_digits(s))
```
输出:
```
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1
9: 1
```
示例输入:
```python
s = "abcde"
print(count_digits(s))
```
输出:
```
None
```
阅读全文