>> words = [y for y in x.split('_')] >>> wo...">

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

+47
python string
Sep 08 '10 at 14:50
source share
7 answers

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 
+49
Sep 08 '10 at 15:00
source share

To verify that all words begin with an uppercase, use this:

 print all(word[0].isupper() for word in words) 
+51
Sep 08 '10 at 14:55
source share
 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" 
+2
Sep 08 2018-10-10
source share

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

+2
Sep 08 '10 at 17:03
source share

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

+1
Sep 08 '10 at 14:53
source share
 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

+1
Apr 01 '15 at 14:05
source share

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

0
09 Oct
source share



All Articles