编写一个字符串统计其中字母和数字字符个数并输出
时间: 2024-05-03 19:21:22 浏览: 16
可以使用Python中的isalnum()函数来判断一个字符是字母或数字。具体实现代码如下:
```python
s = input("请输入字符串:")
letter_count = 0
digit_count = 0
for c in s:
if c.isalnum():
if c.isalpha():
letter_count += 1
elif c.isdigit():
digit_count += 1
print("字母个数:", letter_count)
print("数字个数:", digit_count)
```
运行结果如下:
```
请输入字符串:Hello1234
字母个数: 5
数字个数: 4
```
相关问题
用C语言编写一个字符串,统计其中字母和数字字符个数并输出
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int i, letters = 0, digits = 0;
printf("请输入字符串:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++)
{
if (isalpha(str[i])) // 判断字符是否为字母
{
letters++;
}
else if (isdigit(str[i])) // 判断字符是否为数字
{
digits++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
return 0;
}
```
输入示例:
```
请输入字符串:Hello World! 123
```
输出示例:
```
字母个数:10
数字个数:3
```
编写一个函数,统计字符串中字母、数字、空格 和其它字符个数并输出。
好的,这是一个关于字符串操作的问题。以下是解决方案:
```python
def count_chars(str):
letter, digit, space, other = 0, 0, 0, 0
for i in str:
if i.isalpha():
letter += 1
elif i.isdigit():
digit += 1
elif i.isspace():
space += 1
else:
other += 1
print("字母个数:", letter)
print("数字个数:", digit)
print("空格个数:", space)
print("其他字符个数:", other)
# 测试
str = "Hello World! 123"
count_chars(str)
```
输出结果:
```
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 1
```
希望能够解决您的问题!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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/20210720083512.png)