输入一个字符串,统计字符串中的大写字母个数并输出。定义并调用函数count,返回字符串中大写字母的个数
时间: 2023-11-16 10:15:53 浏览: 74
好的,我来给你写一个 Python 的函数来解决这个问题。代码如下:
```python
def count(s):
count = 0
for c in s:
if c.isupper():
count += 1
return count
```
这个函数定义了一个字符串参数 `s` ,然后遍历了这个字符串中的每一个字符,如果这个字符是大写字母,就将计数器 `count` 增加 1。最后返回计数器的值即可。
你可以这样调用这个函数:
```python
s = input("请输入一个字符串:")
result = count(s)
print("大写字母个数为:", result)
```
这样用户就可以输入一个字符串,然后程序会自动统计其中大写字母的个数并输出。
相关问题
python编写一个函数返回字符串中大写字母个数
好的,以下是一个 Python 函数,可以用来计算字符串中大写字母的数量:
```python
def count_uppercase(s):
count = 0
for c in s:
if c.isupper():
count += 1
return count
```
这个函数接受一个字符串参数 `s`,然后遍历字符串中的每个字符。如果字符是大写字母,那么计数器就加一。最后,函数返回计数器的值,即大写字母的数量。你可以像下面这样调用这个函数:
```python
s = "Hello, World!"
count = count_uppercase(s)
print(count) # 输出:2
```
在这个例子中,字符串 `s` 中有两个大写字母,函数返回值为 2。
定义函数 count(),统计一个字符串中大写字母、小写字母、数字的个数,并以字典为结果返回给调用者
以下是实现该函数的 Python 代码:
```python
def count(s):
# 初始化计数器
result = {'upper': 0, 'lower': 0, 'digit': 0}
# 遍历字符串中的每个字符,并更新计数器
for c in s:
if c.isupper():
result['upper'] += 1
elif c.islower():
result['lower'] += 1
elif c.isdigit():
result['digit'] += 1
# 返回结果字典
return result
```
该函数接受一个字符串参数 `s`,并返回一个字典,其中包含大写字母、小写字母、数字出现的次数。调用该函数的示例如下:
```python
s = 'Hello, World! 123'
result = count(s)
print(result) # 输出:{'upper': 2, 'lower': 8, 'digit': 3}
```