2. 编写函数,接收一个字符串,分别统计大用python写字母、小写字母、数字、其他字符的个数,并以元组形式返回结果,并测试该函数的代码
时间: 2024-05-15 18:13:40 浏览: 11
可以使用Python的内置方法`isupper()`、`islower()`、`isdigit()`来判断字符是否为大写字母、小写字母、数字。其他字符则可以使用正则表达式进行匹配。
以下是代码实现:
```python
import re
def count_chars(s):
upper_count, lower_count, digit_count, other_count = 0, 0, 0, 0
for char in s:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
other_count += len(re.findall("\W", s))
return (upper_count, lower_count, digit_count, other_count)
# 测试
s = "Hello, World! 123"
result = count_chars(s)
print(result)
```
输出结果为:
```
(2, 8, 3, 4)
```
表示大写字母有2个,小写字母有8个,数字有3个,其他字符有4个。
相关问题
编写一个函数,统计字符串大小写和单词个数python
好的,下面是一个简单的 Python 函数,可以统计字符串中的大写字母、小写字母和单词数量:
```python
def count_upper_lower_words(s):
upper_count = 0
lower_count = 0
word_count = len(s.split())
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
return upper_count, lower_count, word_count
```
这个函数接受一个字符串作为输入,然后返回一个包含大写字母计数、小写字母计数和单词数量的元组。你可以通过以下方式调用这个函数:
```python
s = "Hello World! This is a test string."
result = count_upper_lower_words(s)
print(result)
```
输出结果将会是一个元组:
```python
(3, 19, 7)
```
其中,3 表示大写字母数量,19 表示小写字母数量,7 表示单词数量。
编写程序,从键盘输入一个字符串,计算并输出该字符串中的大写字母的个数。
以下是Python的代码实现:
```python
s = input("请输入一个字符串:")
count = 0
for c in s:
if c.isupper():
count += 1
print("大写字母的个数为:", count)
```
首先,我们使用 `input()` 函数从键盘读取一个字符串并将其赋值给变量 `s`。然后,我们定义一个变量 `count` 来记录大写字母的数量,并将其初始化为 0。接下来,使用 `for` 循环遍历字符串中的每个字符,如果该字符是大写字母,则将 `count` 加 1。最后,使用 `print()` 函数输出大写字母的数量。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)