输入一个字符串,统计非数字字母
时间: 2023-04-08 12:02:04 浏览: 139
抱歉,我可以回答这个问题。您可以使用正则表达式来匹配非数字字母的字符,然后统计匹配到的字符数量。以下是一个示例代码:
import re
def count_non_alphanumeric(string):
pattern = r'[^a-zA-Z0-9]'
non_alphanumeric = re.findall(pattern, string)
return len(non_alphanumeric)
string = "Hello, world! 123"
count = count_non_alphanumeric(string)
print(count) # 输出 2,因为有一个空格和一个感叹号是非数字字母字符
相关问题
python输入一串字符串统计字母和数字
可以使用Python编写一个程序来统计输入字符串中的字母和数字。具体步骤如下:
1. 首先,使用input()函数获取用户输入的字符串。
2. 然后,使用for循环遍历字符串中的每个字符。
3. 在循环中,使用isalpha()函数判断字符是否为字母,使用isdigit()函数判断字符是否为数字。
4. 如果字符是字母,则将字母计数器加1;如果字符是数字,则将数字计数器加1。
5. 最后,输出字母计数器和数字计数器的值。
下面是一个示例代码:
```
s = input("请输入一个字符串:")
letter_count = 0
digit_count = 0
for c in s:
if c.isalpha():
letter_count += 1
elif c.isdigit():
digit_count += 1
print("字母个数:", letter_count)
print("数字个数:", digit_count)
```
当用户输入一个字符串后,程序会输出该字符串中字母和数字的个数。
c语言输入一个字符串统计他的字母、数字、空格和其他
可以使用C语言中的字符数组和循环来实现这个功能。具体实现方法如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:\n");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这段代码首先定义一个字符数组 `str`,用于存储输入的字符串,然后使用 `gets` 函数从标准输入中读取字符串。接下来使用一个循环遍历字符串中的每个字符,使用 `isalpha`、`isdigit` 和 `isspace` 函数判断字符是字母、数字还是空格,并分别增加相应的计数器。最后输出各种字符的个数即可。