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

Asked By: lisa

||

Answers:

You can use this regex:

^[A-Z][a-z]*(?:_[A-Z][a-z]*)*$

Sample code:

import re

strings = ["Alpha_beta_Gamma", "Alpha_Beta_Gamma"]
pattern = r'^[A-Z][a-z]*(?:_[A-Z][a-z]*)*$'

for s in strings:
    if re.match(pattern, s):
        print s + " conforms"
    else:
        print s + " doesn't conform"

As seen on codepad

Answered By: NullUserException

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

print all(word[0].isupper() for word in words)
Answered By: Cristian Ciupitu
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"
Answered By: inspectorG4dget

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
Answered By: Jochen Ritzel

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'])

This way you know if is valid and what word is wrong

Answered By: Rafael Sierra

Use list(str) to break into chars then import string and use string.ascii_uppercase to compare against.

Check the string module:
http://docs.python.org/library/string.html

Answered By: Drew Nichols
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 string

Answered By: mihoff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.