python编写函数计算字符串中数字字母的个数 
时间: 2023-05-01 21:06:29 浏览: 31
可以使用Python的内置函数来计算字符串中数字字母的个数。以下是代码示例:
s = 'Hello 123 World'
num_count = 0
char_count = 0
for char in s:
if char.isdigit():
num_count += 1
elif char.isalpha():
char_count += 1
print('数字个数:', num_count)
print('字母个数:', char_count)
输出结果为:
数字个数: 3
字母个数: 10
相关问题
Python编写一个函数计算传入字符串中数字、字母、空格以及其他字符的个数
好的,这个问题我可以回答。请看下面的Python代码:
```python
def count_chars(s):
'''
统计字符串中数字、字母、空格以及其他字符的个数
'''
num_chars = len(s)
num_digits = 0
num_letters = 0
num_spaces = 0
num_others = 0
for c in s:
if c.isdigit():
num_digits += 1
elif c.isalpha():
num_letters += 1
elif c.isspace():
num_spaces += 1
else:
num_others += 1
return (num_chars, num_digits, num_letters, num_spaces, num_others)
# 测试一下
s = 'hello, 123 world!'
print(count_chars(s)) # 输出 (16, 3, 10, 2, 1)
```
以上函数可以接收一个字符串参数`s`,并统计出其中数字、字母、空格以及其他字符的个数。函数返回一个包含五个元素的元组,分别表示字符串`s`的总字符数、数字个数、字母个数、空格个数以及其他字符个数。示例中,输入字符串`'hello, 123 world!'`,输出结果为`(16, 3, 10, 2, 1)`,其中有16个字符,其中3个是数字,10个是字母,2个是空格,1个是逗号。
编写函数,计算传入的字符串中数字,字母,空格和其他字符的个数
以下是一个Python函数,可以计算传入的字符串中数字、字母、空格和其他字符的个数:
```python
def count_chars(s):
num_count = 0
letter_count = 0
space_count = 0
other_count = 0
for c in s:
if c.isdigit():
num_count += 1
elif c.isalpha():
letter_count += 1
elif c.isspace():
space_count += 1
else:
other_count += 1
return num_count, letter_count, space_count, other_count
```
该函数接受一个字符串作为参数,然后遍历字符串中的每个字符,根据字符的类型分别累加数字、字母、空格和其他字符的个数。最后,函数返回一个包含四个计数值的元组。
例如,如果我们调用该函数并传入字符串"Hello, 123!",则会返回元组(3, 5, 1, 2),表示该字符串中包含3个数字、5个字母、1个空格和2个其他字符。
相关推荐









