我是一个绝对的初学者,我无法弄清楚为什么我的代码没有给出预期的结果。我想编写一个函数,计算给定字符串中大小写字母的数量。示例如下。
String:“你好,Rogers先生,你星期二过得怎么样? 预期输出:
不。大写字母:4
不。小写字符:33
def up_low(s):
upper_case_count = 0
lower_case_count = 0
split_s = s.split()
for word in split_s:
if word.islower() == False:
upper_case_count +=1
lower_case_count += len(word) - 1
elif word.islower() == True:
letter_count = len(word)
lower_case_count += letter_count
print(f'No. of Upper case characters is {upper_case_count}')
print(f'No. of Lower case characters is {lower_case_count}')
如果运行在上一个示例中编写的函数,则得到4和36,而不是33。此外,我非常确定我编写的内容还是不正确的,因为仅当字符串中的单词具有只能有一个大写字母,但是我不知道如何解决这个问题,以便无论单词中有多少个大写字母都可以
答案 0 :(得分:4)
分别用于小写和大写计数(字符串在a
中)
sum(i.islower() for i in a)
sum(i.isupper() for i in a)
并感谢@Jean-FrançoisFabre使用map
的建议。
sum(map(str.islower,a))
sum(map(str.isupper,a))
完整程序
print(f"The number of lower case characters is {sum(map(str.islower,a))}")
print(f"The number of upper case characters is {sum(map(str.isupper,a))}")
答案 1 :(得分:0)
#!/usr/bin/env python3
def up_low(s):
upper_case_count = 0
lower_case_count = 0
for letter in s:
#If letter is uppercase, add 1 to upper count
if letter.isupper():
upper_case_count +=1
#If letter is lowercase, add 1 to upper count
if letter.islower() == True:
lower_case_count +=1
#All other characters, such as punctuation and questions, will be ignored.
print('No. of Upper case characters is {}'.format(upper_case_count))
print('No. of Upper case characters is {}'.format(lower_case_count))
s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
up_low(s)
输出:
No. of Upper case characters is 4
No. of Upper case characters is 33
答案 2 :(得分:0)
def up_low(s):
upper_case_count = 0
lower_case_count = 0
for char in s:
if char.isupper():
upper_case_count += 1
elif char.islower():
lower_case_count += 1
print(f'No. of Upper case characters is {upper_case_count}')
print(f'No. of Lower case characters is {lower_case_count}')