用Python在函数体内计算字符串中数字,字母,空格以及其他字符的个数
时间: 2024-12-14 14:20:38 浏览: 6
Python基础之字符串操作常用函数集合
在 Python 中,你可以编写一个函数来统计字符串中数字、字母、空格和其他字符的数量。这里是一个简单的示例:
```python
def count_chars(s):
num_digits = sum(c.isdigit() for c in s)
num_letters = sum(c.isalpha() for c in s)
num_spaces = s.count(' ')
other_chars = len(s) - num_digits - num_letters - num_spaces
return num_digits, num_letters, num_spaces, other_chars
# 使用示例
input_string = "Hello World! This is a test string with 123 numbers."
digits, letters, spaces, others = count_chars(input_string)
print(f"Numbers: {digits}")
print(f"Letters: {letters}")
print(f"Spaces: {spaces}")
print(f"Other Characters (including punctuation): {others}")
阅读全文