用 python 统计字符串中数字,字符,汉字和其他字符的个数
时间: 2024-06-10 12:07:17 浏览: 7
好的,这个问题很简单。你可以使用 Python 的isnumeric()、isalpha()、isdigit()函数,以及isalnum()函数统计字符串中数字,字符,汉字和其他字符的个数。以下是示例代码:
```
string = "你好,hello, 2021!, qwerty@"
num_count = 0
alpha_count = 0
chinese_count = 0
other_count = 0
for i in string:
if i.isnumeric():
num_count += 1
elif i.isalpha():
alpha_count += 1
elif i.isalnum():
chinese_count += 1
else:
other_count += 1
print('数字个数:', num_count)
print('字符个数:', alpha_count)
print('汉字个数:', chinese_count)
print('其他字符个数:', other_count)
```
输出结果为:
```
数字个数: 4
字符个数: 9
汉字个数: 7
其他字符个数: 3
```
希望能对您有所帮助!
相关问题
用python统计字符串中数字的个数的代码
可以使用 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。最后输出数字的个数。