简体   繁体   中英

How to check if all characters in a string are capitalized using a loop

I am trying to check if each character in my string is capitalized. I have to use a loop, and cannot use regex. My idea is that the loop checks each character whether or not it is both capitalized and a known character. If it gets to a character that is not both capitalized and known, it exits the loop and returns false, otherwise it returns true.

        for i in range(len(s)):
            char = s[i]
            if is_capitalized(char):
                return True
            else:
                return False
                break
    else: 
        return False

Here is the docstring of how the function is supposed to behave. For some reason, is_all_caps('CHATte') returns True.

    >>> is_all_caps('HA')
    True
    >>> is_all_caps('CHAT')
    True
    >>> is_all_caps('CHATte')
    False

This is because as soon as a function returns a value, it ends and does not continue. Thus, as soon as it reaches a capitalised character ( if is_capitalized(char) ), it will return True and not check the rest of the characters.

You can take advantage of this and immediately return False once you see an invalid character, and if the for-loop reaches the end, then you know that all your characters must be valid (capitalised):

for i in range(len(s)):
    char = s[i]
    if not is_capitalized(char):
        return False

return True

You don't even need regex for this. You can use isupper() like this:

def is_all_caps(s):
    return all(char.isupper() for char in s)
>>> is_all_caps('HA')
True
>>> is_all_caps('CHAT')
True
>>> is_all_caps('CHATte')
False

Or why not simply comparing the string to its fully capitalized version?

s == s.upper()  # returns True if all characters in the string are capitalized (or False if any of them is not)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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