如何检查一个字符在Python中是否大写?
我有这样的一个string
>>> x="Alpha_beta_Gamma" >>> words = [y for y in x.split('_')] >>> words ['Alpha', 'beta', 'Gamma']
我想输出说X不符合,因为列表单词的第二个元素以小写字母开头,如果stringx = "Alpha_Beta_Gamma"
那么它应该打印string是一致的
也许你想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
要testing所有单词以大写字母开头,请使用以下命令:
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"
你可以使用这个代码:
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'])
这样,你知道是否有效,什么字是错的
你可以使用这个正则expression式:
^[AZ][az]*(?:_[AZ][az]*)*$
示例代码:
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"
正如在键盘上看到的
x="Alpha_beta_Gamma" is_uppercase_letter = True in map(lambda l: l.isupper(), x) print is_uppercase_letter >>>>True
所以你可以用1个string来写
使用列表(str)分解为字符,然后导入string并使用string.ascii_uppercase进行比较。
检查string模块: http : //docs.python.org/library/string.html