def Charater():
UpperCount = 0
LowerCount = 0
word = input('Enter a word: ')
for letter in word:
if letter == letter.upper
UpperCount = UpperCount + 1
return UpperCount
else:
LowerCount = LowerCount + 1
return LowerCount
print(Charater())
如果这看起来不好,请不要评价我。但我是初学者,我试图让代码计算用户输入的单词中有多少个大写和小写字符。每次我这样做它返回1.(它可能是我的if语句)。有人可以指出问题并告诉我如何解决它。
答案 0 :(得分:3)
您可以使用map
与str.isupper
和str.islower
分别查找大写和小写字符的计数:
>>> my_word = "HelLo WorLd"
>>> lower_count = sum(map(str.islower, my_word))
>>> lower_count
6
>>> upper_count = sum(map(str.isupper, my_word))
>>> upper_count
4
答案 1 :(得分:0)
作为一个简短的功能
def count_up_and_low(word):
u = [x for x in word if x.isupper()]
l = [x for x in word if x.islower()]
return len(u), len(v)
答案 2 :(得分:0)
这应该有效
def count_by_case(string):
upper = sum(letter.isupper() for letter in string)
lower = sum(letter.islower() for letter in string)
return lower, upper
string = "MyString"
lower, upper = count_by_case(string)
print("{!r} contains {} upper and {} lower case letters".format(string, upper, lower))
答案 3 :(得分:0)
使用$post_data
and
var postdata
,生成器理解和嵌套三元组计算一行:
collections.Counter
结果:
import collections
my_word = "HelLo WorLd"
c = collections.Counter("upper" if x.isupper() else "lower" if x.islower() else "" for x in my_word)
print(c)
答案 4 :(得分:0)
def up_low(str):
upper_count=0
lower_count=0
for x in str:
if x.isupper():
upper_count+=1
else:
lower_count+=1
print(f'number of upper case letter {upper_count}')
print(f'number of lower case letter {lower_count}')