python编写一个函数,统计一个字符串中大写字母的个数。利用函数编程统计一个字符串元组中大写字母出现的次数。
时间: 2024-05-01 13:16:27 浏览: 17
1. 统计一个字符串中大写字母的个数:
```python
def count_uppercase(s):
count = 0
for c in s:
if c.isupper():
count += 1
return count
s = "Hello World!"
print(count_uppercase(s)) # 输出 2
```
2. 利用函数编程统计一个字符串元组中大写字母出现的次数:
```python
def count_uppercase(s):
count = 0
for c in s:
if c.isupper():
count += 1
return count
t = ("Hello World!", "Welcome to Python", "I am a PYTHON programmer")
counts = list(map(count_uppercase, t))
print(counts) # 输出 [2, 2, 6]
```
注:上面代码中,利用 `map` 函数对元组中每个字符串调用 `count_uppercase` 函数,返回一个包含每个字符串中大写字母出现次数的列表。
相关问题
编写一个函数统计字符串中大写字母和小写字母的个数
好的,以下是实现这个功能的 Python 代码:
```python
def count_upper_lower(s):
upper_count = 0
lower_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
return upper_count, lower_count
```
这个函数接受一个字符串作为参数,然后遍历字符串中的每个字符,判断它是大写字母还是小写字母,最后返回一个元组,包含大写字母的数量和小写字母的数量。你可以调用这个函数来统计任何字符串中大写字母和小写字母的个数,例如:
```python
s = "Hello, World!"
upper_count, lower_count = count_upper_lower(s)
print("大写字母数量:", upper_count)
print("小写字母数量:", lower_count)
```
输出结果为:
```
大写字母数量: 2
小写字母数量: 8
```
定义一个函数,分别返回字符串中大写,小写和数字字母的个数
以下是Python的实现:
```python
def count_chars(s):
upper_count = 0
lower_count = 0
digit_count = 0
for char in s:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
return upper_count, lower_count, digit_count
```
该函数接受一个字符串作为参数,并遍历字符串中的每个字符。对于每个字符,它使用`isupper()`、`islower()`和`isdigit()`方法检查它是否是大写字母、小写字母或数字。如果是,就将相应的计数器加1。最后,该函数返回一个包含三个值的元组,分别是大写字母、小写字母和数字的个数。