How to check if a character is upper-case in Python?


Question

I have a string like this

>>> x="Alpha_beta_Gamma"
>>> words = [y for y in x.split('_')]
>>> words
['Alpha', 'beta', 'Gamma']

I want output saying X is non conformant as the the second element of the list words starts with a lower case and if the string x = "Alpha_Beta_Gamma" then it should print string is conformant

1
66
9/8/2010 5:08:12 PM

Accepted Answer

Maybe you want str.istitle

>>> help(str.istitle)
Help on method_descriptor:

istitle(...)
    S.istitle() -> bool

    Return True if S is a titlecased string and there is at least one
    character in S, i.e. uppercase characters may only follow uncased
    characters and lowercase characters only cased ones. Return False
    otherwise.

>>> "Alpha_beta_Gamma".istitle()
False
>>> "Alpha_Beta_Gamma".istitle()
True
>>> "Alpha_Beta_GAmma".istitle()
False
58
2/18/2016 9:05:27 PM

To test that all words start with an upper case use this:

print all(word[0].isupper() for word in words)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon