Python统计不同字符个数。对于输入的一行字符,统计英文、数字、空格和其他字符的个数。
时间: 2024-03-22 09:14:08 浏览: 32
好的,这个问题可以回答。
以下是 Python 代码实现:
```
s = input("请输入一行字符:")
alpha_num, digit_num, space_num, other_num = 0, 0, 0, 0
for c in s:
if c.isalpha():
alpha_num += 1
elif c.isdigit():
digit_num += 1
elif c.isspace():
space_num += 1
else:
other_num += 1
print("英文字母个数为:", alpha_num)
print("数字个数为:", digit_num)
print("空格个数为:", space_num)
print("其他字符个数为:", other_num)
```
输入示例:Hello World! 123
输出示例:
```
英文字母个数为: 10
数字个数为: 3
空格个数为: 2
其他字符个数为: 1
```
相关问题
python输入一行字符统计英文字母和空格数字和其它字符的个数
这道题目要求我们输入一行字符,然后分别统计其中英文字母、空格、数字和其它字符的个数。可以使用 Python 代码来实现。以下是一个例子:
```
line = input("请输入一行字符:")
letters = 0
spaces = 0
digits = 0
others = 0
for i in line:
if i.isalpha():
letters += 1
elif i.isspace():
spaces += 1
elif i.isdigit():
digits += 1
else:
others += 1
print("在输入的字符串中,有{}个字母,{}个空格,{}个数字,{}个其它字符。".format(letters, spaces, digits, others))
```
这段代码首先让用户输入一行字符,然后遍历每个字符,判断它是字母、空格、数字还是其它字符,并分别统计它们的个数。最后输出结果。
--相关问题--:
写一个Python程序 使输入一行字符 统计其中英文字母 空格数字和其他字符的个数
当然,可以的。以下是Python程序代码:
```
str = input("请输入一行字符:")
letter = 0
space = 0
digit = 0
others = 0
for c in str:
if c.isalpha():
letter += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print("在输入中,英文字母的个数为:%d,空格的个数为:%d,数字的个数为:%d,其他字符的个数为:%d" % (letter, space, digit, others))
```
您可以将上述代码复制并粘贴到Python开发环境中,并运行它。这个程序将会让您输入一行字符,并统计该字符中的英文字母、空格、数字和其他字符的个数,并在屏幕上显示出来。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)