给出一串字符,要求统计出里面的字母、数字、空格以及其他字符的个数。 字母:a, b, ..., z、a, b, ..., z组成 数字:0, 1, ..., 9 空格:" "(不包括引号) 剩下的可打印字符全为其他字符。
时间: 2023-04-27 15:01:32 浏览: 87
可以使用循环遍历字符串中的每个字符,然后根据字符的类型进行计数。具体实现如下:
```
string = "Hello, world! 123"
letter_count =
digit_count =
space_count =
other_count =
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
space_count += 1
else:
other_count += 1
print("字母个数:", letter_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
print("其他字符个数:", other_count)
```
输出结果为:
```
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 2
```
相关问题
分别统计出一串字符中英文字母数字空格和其他字符的个数
好的,我可以帮你解决这个问题。你可以将这个问题分解成以下几个步骤:
1. 遍历字符串中的每个字符。
2. 使用 Python 中的内置函数 isalpha()、isdigit()、isspace() 判断字符属于哪一类。
3. 维护四个变量,分别用于统计英文字母、数字、空格和其他字符的个数。
4. 最后输出这四个变量的值即可。
下面是一个 Python 函数,可以实现上述功能:
```python
def count_chars(s):
n_alpha = n_digit = n_space = n_other = 0
for c in s:
if c.isalpha():
n_alpha += 1
elif c.isdigit():
n_digit += 1
elif c.isspace():
n_space += 1
else:
n_other += 1
return n_alpha, n_digit, n_space, n_other
```
这个函数接受一个字符串作为输入,返回一个包含四个整数的元组,分别表示英文字母、数字、空格和其他字符的个数。你可以使用以下代码调用这个函数:
```python
s = "Hello, 123 world! \t"
n_alpha, n_digit, n_space, n_other = count_chars(s)
print("英文字母:", n_alpha)
print("数字:", n_digit)
print("空格:", n_space)
print("其他字符:", n_other)
```
这个例子中的输出结果应该是:
```
英文字母: 10
数字: 3
空格: 4
其他字符: 3
```
输入一行字符串,分别统计出其中英文字母、空格、数字和其它字符的个数
好的,可以使用 Python 编写一个程序来解决这个问题。代码如下:
```python
string = input("请输入一行字符串:")
letters = 0
spaces = 0
digits = 0
others = 0
for char in string:
if char.isalpha():
letters += 1
elif char.isspace():
spaces += 1
elif char.isdigit():
digits += 1
else:
others += 1
print("英文字母:", letters)
print("空格:", spaces)
print("数字:", digits)
print("其它字符:", others)
```
运行程序后,输入一行字符串,程序会输出其中英文字母、空格、数字和其它字符的个数。注意,如果输入的字符串中包含中文等非英文字符,这些字符会被视为其它字符进行统计。