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

时间:2010-09-08 14:50:14

标签: python string

我有一个像这样的字符串

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

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

7 个答案:

答案 0 :(得分:74)

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

print all(word[0].isupper() for word in words)

答案 1 :(得分:58)

也许你想要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

答案 2 :(得分:3)

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

所以你可以用1个字符串写

答案 3 :(得分:2)

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"

答案 4 :(得分:2)

您可以使用此代码:

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

这样你就知道是否有效以及哪个词出错了

答案 5 :(得分:1)

您可以使用此正则表达式:

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

示例代码:

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"

codepad

答案 6 :(得分:-1)

使用list(str)分解字符然后导入字符串并使用string.ascii_uppercase进行比较。

检查字符串模块: http://docs.python.org/library/string.html