3、用python输入一个字符串,判断字符串中有多少个字母?多少个数字?多少个其他符号?
时间: 2023-11-27 08:54:51 浏览: 61
可以使用Python中的字符串方法和循环来实现这个功能。以下是一个示例代码:
```python
string = input("请输入一个字符串:")
letter_count = 0
digit_count = 0
other_count = 0
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print("字母个数:", letter_count)
print("数字个数:", digit_count)
print("其他符号个数:", other_count)
```
代码中,首先使用`input`函数获取用户输入的字符串。然后,通过循环遍历字符串中的每个字符,使用`isalpha`方法判断是否为字母,使用`isdigit`方法判断是否为数字,否则就表示为其他符号。最后,输出三种类型字符的个数。
相关问题
输入一个字符串,判断字符串中有多少个字母?多少个数字?多少个其他符号?
可以使用Python的字符串处理函数和正则表达式来实现。以下是一个示例代码:
```python
import re
s = input("请输入一个字符串:")
letter_count = 0
digit_count = 0
other_count = 0
for c in s:
if c.isalpha():
letter_count += 1
elif c.isdigit():
digit_count += 1
else:
other_count += 1
# 也可以使用正则表达式来实现
# letter_count = len(re.findall(r'[a-zA-Z]', s))
# digit_count = len(re.findall(r'\d', s))
# other_count = len(re.findall(r'[^a-zA-Z\d]', s))
print("字母数量:", letter_count)
print("数字数量:", digit_count)
print("其他符号数量:", other_count)
```
示例输出:
```
请输入一个字符串:Hello, world! 123.
字母数量: 10
数字数量: 3
其他符号数量: 4
```
编写一个Python程序,要求能输入一个字符串,判断字符串中有多少个字母?多少个数字?多少个其他符号?
```
string = input("请输入一个字符串:")
letter_count = 0
digit_count = 0
other_count = 0
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print("字符串中有{}个字母,{}个数字,{}个其他符号。".format(letter_count, digit_count, other_count))
```
注:isalpha()方法用于判断一个字符是否为字母,isdigit()方法用于判断一个字符是否为数字。