Python:我的代码有错误,我不知道如何解决

时间:2019-02-01 16:54:35

标签: python string

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

3 个答案:

答案 0 :(得分:1)

尝试:

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

答案 1 :(得分:0)

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

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])

答案 2 :(得分:-1)

def upper_lower(s):
    s = ''.join(c for c in s if c.isalpha())
    return bool(s) and (s.isupper() or s.islower())