Check if all characters of a string are uppercase

61,196

Solution 1

You should use str.isupper() and str.isalpha() function.

Eg.

is_all_uppercase = word.isupper() and word.isalpha()

According to the docs:

S.isupper() -> bool

Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.

Solution 2

You could use regular expressions:

all_uppercase = bool(re.match(r'[A-Z]+$', word))

Solution 3

Yash Mehrotra has the best answer for that problem, but if you'd also like to know how to check that without the methods, for purely educational reasons:

import string

def is_all_uppercase(a_str):
    for c in a_str:
        if c not in string.ascii_uppercase:
            return False
    return True

Solution 4

Here you can find a very useful way to check if there's at least one upper or lower letter in a string

Here's a brief example of what I found in this link:

print(any(l.isupper() for l in palabra))

https://www.w3resource.com/python-exercises/python-basic-exercise-128.php

Share:
61,196

Related videos on Youtube

ffgghhffgghh
Author by

ffgghhffgghh

Updated on April 13, 2021

Comments

  • ffgghhffgghh
    ffgghhffgghh about 3 years

    Say I have a string that can contain different characters:

    e.g. word = "UPPER£CASe"

    How would I test the string to see if all the characters are uppercase and no other punctuation, numbers, lowercase letters etc?

  • ffgghhffgghh
    ffgghhffgghh over 8 years
    This also shows True if it contains a number or punctuation mark for example. I need it so it is only uppercase letters (A-Z). Thanks
  • ffgghhffgghh
    ffgghhffgghh over 8 years
    This also shows True if it contains a number or punctuation mark for example. I need it so it is only uppercase letters (A-Z). Thanks
  • MestreLion
    MestreLion about 3 years
    Be aware that this is does not restrict to ASCII characters, it will allow uppercase Greek and Cyrilic for example. Which may or may not be what you want.
  • MestreLion
    MestreLion about 3 years
    This yields True for "ΓΔΘΞΠΦΨΩБГДЖЙЛ", so beware. Well, they are uppercase letters.. just not English ones.
  • MestreLion
    MestreLion about 3 years
    That's an incredibly inefficient code in every step: if you really want to use a character-level approach, instead of a list comprehension with a len() test that needlessly tests all chars even when the first fails, use a generator expression with any()/all() so it short-circuits on the first failed character.