[英]Python: Error in my code and i don't know how to fix it
The example below is failing upper_lower('abcXYZ')
, it returns true下面的示例失败upper_lower('abcXYZ')
,它返回 true
def upper_lower(s: str) -> bool:
"""Return True if and only if there is at least one alphabetic character
in s and the alphabetic characters in s are either all uppercase or all
lowercase.
>>> upper_lower('abc')
True
>>> upper_lower('abcXYZ')
False
>>> upper_lower('XYZ')
True
"""
for char in s:
if char.isalpha():
if char.isupper() or char.islower():
return True
if char.swapcase():
return False
else:
return False
Try that:试试看:
def upper_lower(s):
return s.isupper() or s.islower()
print(upper_lower("abc")) # True
print(upper_lower("12abc45")) # True
print(upper_lower("ABC")) # True
print(upper_lower("ABC45")) # True
print(upper_lower("aBC")) # False
print(upper_lower("123")) # False
Your code currently returns True if the first alpha character is eiher lowcase or upcase:如果第一个字母字符是小写或大写,您的代码当前返回 True:
if char.isupper() or char.islower():
return True # return cause the function to end, other cars are not tested
I would suggest using list comprehension for this:我建议为此使用列表理解:
def upper_lower(word):
if not word:
return False
else:
return all([s.isupper() for s in word]) or all([s.islower() for s in word])
def upper_lower(s):
s = ''.join(c for c in s if c.isalpha())
return bool(s) and (s.isupper() or s.islower())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.