用python统计字符串中数字的个数的代码
时间: 2023-09-25 21:12:45 浏览: 39
可以使用 Python 的内置函数 isdigit() 和 count() 来统计字符串中数字的个数,代码如下:
```
string = input("请输入字符串:")
count = 0
for char in string:
if char.isdigit():
count += 1
print("字符串中数字的个数为:", count)
```
其中,`string` 为用户输入的字符串,`count` 用于统计数字的个数,`for` 循环遍历字符串中的每个字符,`isdigit()` 函数判断字符是否为数字,如果是,则计数器 `count` 加 1,最后输出数字的个数。
相关问题
python统计字符串中数字的个数代码
以下是统计字符串中数字个数的Python代码:
```python
string = "hello123world456"
count = 0
for i in string:
if i.isdigit():
count += 1
print("字符串中数字的个数为:", count)
```
运行代码,输出结果为:
```
字符串中数字的个数为: 6
```
这个代码遍历字符串中的每个字符,如果字符是数字,则计数器加1。最后输出数字的个数。
用 python 统计字符串中数字,字符,汉字和其他字符的个数
很高兴回答您的问题!对于您提出的问题,我可以提供以下代码来统计字符串中数字,字符,汉字和其他字符的个数:
```python
str = input("请输入一个字符串:")
num = 0
char = 0
chinese = 0
other = 0
for i in str:
if i.isdigit():
num += 1
elif i.isalpha():
char += 1
elif i.isalnum():
other += 1
else:
chinese += 1
print("数字个数:", num)
print("字母个数:", char)
print("汉字个数:", chinese)
print("其他字符个数:", other)
```
注意,以上代码只能识别一个字符串中的数字,字符,汉字和其他字符的个数,无法识别多个字符串。如果您需要处理多个字符串,请将代码包装在循环语句中并依次输入每个字符串。