繁体   English   中英

Python:我的代码出错,我不知道如何修复它

[英]Python: Error in my code and i don't know how to fix it

下面的示例失败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

试试看:

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

如果第一个字母字符是小写或大写,您的代码当前返回 True:

if char.isupper() or char.islower():
    return True   # return cause the function to end, other cars are not tested

我建议为此使用列表理解:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM