您可以使用以下代码来编写自定义函数,统计字符串中小写字母的个数:
def count_lowercase_letters(string):
count = 0
for character in string:
if character.islower():
count += 1
return count
该函数使用一个循环来遍历字符串中的每个字符,并使用 Python 的 islower() 方法来判断该字符是否是小写字母。如果是,则将计数器增加 1。最后,函数返回计数器的值。
下面是一个示例,展示如何使用该函数:
string = "Hello World!"
count = count_lowercase_letters(string)
print(count) # Output: 3
在此示例中,字符串 "Hello World!" 中有 3 个小写字母,因此输出为 3。
温馨提示:答案为网友推荐,仅供参考