3. 使用 for in 语句,while 语句,以及 for in range ()语句,等 3 种方 式,统计用户输入的字符串中,字母和数字的个数。并给出测试用例。
时间: 2024-10-16 09:17:07 浏览: 15
Python3之for和while循环语句
在Python中,有多种方法可以统计用户输入的字符串中字母和数字的数量。以下是三种常见方式:
1. **for in 语句(遍历字符串每个字符)**:
```python
def count_chars(input_str):
count = {'letters': 0, 'numbers': 0}
for char in input_str:
if char.isalpha():
count['letters'] += 1
elif char.isdigit():
count['numbers'] += 1
return count
test_case_1 = "Hello123"
print(count_chars(test_case_1))
```
2. **while 语句(手动迭代直到遍历完字符串)**:
```python
def count_chars_manual(input_str):
count = {'letters': 0, 'numbers': 0}
index = 0
while index < len(input_str):
char = input_str[index]
if char.isalpha():
count['letters'] += 1
elif char.isdigit():
count['numbers'] += 1
index += 1
return count
test_case_2 = "Python456"
print(count_chars_manual(test_case_2))
```
3. **for in range() 语句(适用于已知长度的字符串)**:
```python
def count_chars_range(input_str):
count = {'letters': 0, 'numbers': 0}
for i in range(len(input_str)):
char = input_str[i]
if char.isalpha():
count['letters'] += 1
elif char.isdigit():
count['numbers'] += 1
return count
test_case_3 = "ABC123 DEF456"
print(count_chars_range(test_case_3))
```
上述测试用例的结果将分别返回包含字母和数字个数的字典。
阅读全文