输入一个字符串,统计出这个字符串的英文大写字母、小写字母、数字、空格以及其它字符的个数
时间: 2023-04-16 21:01:47 浏览: 106
输入一行字符,分别统计出其中英文字母、空格数字和其它字符的个数.docx
5星 · 资源好评率100%
可以使用 Python 中的字符串方法和正则表达式来统计字符串中各类字符的个数。
示例代码:
```python
import re
def count_chars(string):
upper_count = 0
lower_count = 0
digit_count = 0
space_count = 0
other_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
space_count += 1
else:
other_count += 1
return upper_count, lower_count, digit_count, space_count, other_count
string = "Hello World! 123"
upper, lower, digit, space, other = count_chars(string)
print("Upper:", upper)
print("Lower:", lower)
print("Digit:", digit)
print("Space:", space)
print("Other:", other)
```
输出结果如下:
```
Upper: 2
Lower: 8
Digit: 3
Space: 1
Other: 2
```
也可以使用正则表达式来统计每种字符的个数
```python
import re
def count_chars(string):
upper_count = len(re.findall(r'[A-Z]',string))
lower_count = len(re.findall(r'[a-z]',string))
digit_count = len(re.findall(r'[0-9]',string))
space_count = len(re.findall(r'[ ]',string))
other_count = len(re.findall(r'[^A-Za-z0-9 ]',string))
return upper_count, lower_count, digit_count, space_count, other_count
string = "Hello World! 123"
upper, lower, digit, space, other = count_chars(string)
print("Upper:", upper)
print("Lower:", lower)
print("Digit:", digit)
print("Space:", space)
print("Other:", other)
```
输出结果如下:
```
Upper: 2
Lower: 8
Digit: 3
Space: 1
Other: 2
```
阅读全文