How to check if a character is uppercase in Python?
I have a line like this
>>> x="Alpha_beta_Gamma" >>> words = [y for y in x.split('_')] >>> words ['Alpha', 'beta', 'Gamma'] I want the output saying that X does not match, since the second element of the list word starts in lowercase, and if the line x = "Alpha_Beta_Gamma" , then it should print the line consistently
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, ie 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 To verify that all words begin with an uppercase, use this:
print all(word[0].isupper() for word in words) words = x.split("_") for word in words: if word[0] == word[0].upper() and word[1:] == word[1:].lower(): print word, "is conformant" else: print word, "is non conformant" You can use this code:
def is_valid(string): words = string.split('_') for word in words: if not word.istitle(): return False, word return True, words x="Alpha_beta_Gamma" assert is_valid(x)==(False,'beta') x="Alpha_Beta_Gamma" assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma']) So you know if it is valid and which word is wrong
You can use this regex:
^[AZ][az]*(?:_[AZ][az]*)*$ Code example:
import re strings = ["Alpha_beta_Gamma", "Alpha_Beta_Gamma"] pattern = r'^[AZ][az]*(?:_[AZ][az]*)*$' for s in strings: if re.match(pattern, s): print s + " conforms" else: print s + " doesn't conform" As seen on codepad
x="Alpha_beta_Gamma" is_uppercase_letter = True in map(lambda l: l.isupper(), x) print is_uppercase_letter >>>>True So you can write it in 1 line
Use a list (str) to break into characters, then import the string and use string.ascii_uppercase for comparison.
Check out the string module: http://docs.python.org/library/string.html