Python 字符串统计:数字、小写字母和大写字母个数 (while & for 循环)
使用 'while' 循环和 'for' 循环都可以统计一个字符串中数字、小写字母和大写字母的个数。以下是使用 'while' 循环和 'for' 循环分别实现该功能的示例代码:
使用 'while' 循环:
string = 'Hello123World'
digits = 0
lowercase = 0
uppercase = 0
index = 0
while index < len(string):
if string[index].isdigit():
digits += 1
elif string[index].islower():
lowercase += 1
elif string[index].isupper():
uppercase += 1
index += 1
print('Digits:', digits)
print('Lowercase letters:', lowercase)
print('Uppercase letters:', uppercase)
使用 'for' 循环:
string = 'Hello123World'
digits = 0
lowercase = 0
uppercase = 0
for char in string:
if char.isdigit():
digits += 1
elif char.islower():
lowercase += 1
elif char.isupper():
uppercase += 1
print('Digits:', digits)
print('Lowercase letters:', lowercase)
print('Uppercase letters:', uppercase)
输出结果为:
Digits: 3
Lowercase letters: 8
Uppercase letters: 3
以上是统计字符串中数字、小写字母和大写字母个数的示例代码和结果。你可以根据需要进行相应的调整。
原文地址: https://www.cveoy.top/t/topic/bn21 著作权归作者所有。请勿转载和采集!