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
To test that all words start with an upper case use this:
print all(word[0].isupper() for word in words)
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
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
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
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
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"
Source: Stackoverflow.com