如何在Python中检查字符是否为大写?

lis*_*isa 68 python string

我有这样的字符串

>>> x="Alpha_beta_Gamma"
>>> words = [y for y in x.split('_')]
>>> words
['Alpha', 'beta', 'Gamma']
Run Code Online (Sandbox Code Playgroud)

我想输出说X是不符合的,因为列表单词的第二个元素以小写字母开头,如果字符串x = "Alpha_Beta_Gamma"那么它应该打印字符串是符合的

Cri*_*itu 78

要测试所有单词以大写字母开头,请使用:

print all(word[0].isupper() for word in words)
Run Code Online (Sandbox Code Playgroud)

  • @lisa:在Python3中使用`print(all ...)`因为`print`是一个函数,而不是一个语句. (2认同)

Joc*_*zel 60

也许你想要 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
Run Code Online (Sandbox Code Playgroud)


小智 5

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True
Run Code Online (Sandbox Code Playgroud)

所以你可以把它写成 1 个字符串