用Python编写一个函数,由实参传来一个字符串中字母、数字、空格的个数,编写代码请用户输入字符串,并输出上述结果。
时间: 2024-03-02 07:50:26 浏览: 15
可以使用Python内置函数isalnum()、isdigit()和isspace()来判断字符串中的字母、数字和空格。以下是对应的代码实现:
```python
def count_chars(string):
alpha_count = 0
digit_count = 0
space_count = 0
for char in string:
if char.isalnum():
alpha_count += 1
if char.isdigit():
digit_count += 1
if char.isspace():
space_count += 1
return alpha_count, digit_count, space_count
string = input("请输入一个字符串:")
alpha_count, digit_count, space_count = count_chars(string)
print("字母个数:", alpha_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
```
使用input函数获取用户输入的字符串,然后调用count_chars函数统计字母、数字和空格的个数,并输出结果。
相关问题
编写一个程序由实参传来一个字符串统计字符串中数字,字母,空格和其他字符的个数
以下是Python程序实现:
```python
def count_chars(s):
digits = letters = spaces = others = 0
for char in s:
if char.isdigit():
digits += 1
elif char.isalpha():
letters += 1
elif char.isspace():
spaces += 1
else:
others += 1
return digits, letters, spaces, others
s = input("请输入一个字符串:")
digits, letters, spaces, others = count_chars(s)
print("数字的个数为:", digits)
print("字母的个数为:", letters)
print("空格的个数为:", spaces)
print("其他字符的个数为:", others)
```
首先定义了一个函数`count_chars`,接收一个字符串`s`作为参数,并返回数字、字母、空格、其他字符的个数。
然后在函数内部定义四个变量`digits`、`letters`、`spaces`、`others`,分别表示数字、字母、空格、其他字符的个数,初始值均为0。
接着使用for循环遍历字符串`s`中的每一个字符,判断其属于哪一类字符,并将对应的计数器加1。
最后返回四个计数器的值。
在主程序中,首先接收用户输入的字符串,并调用`count_chars`函数统计各种字符的个数。
最后输出结果。
编写一个函数由实参传来一个字符串统计此字符串中字母数字空格和其他字符的个数在主函数中输入字符串以及输出上述的结果
以下是 Python 代码实现:
```python
def count_chars(string):
letters = 0
digits = 0
spaces = 0
others = 0
for char in string:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
print("字母个数:", letters)
print("数字个数:", digits)
print("空格个数:", spaces)
print("其他字符个数:", others)
# 主函数
if __name__ == '__main__':
string = input("请输入一个字符串: ")
count_chars(string)
```
示例输出:
```
请输入一个字符串: Hello World! 123
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 1
```