如何在 Python 中检查字符是否为大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3668964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a character is upper-case in Python?
提问by lisa
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
我想要输出说 X 不符合,因为列表单词的第二个元素以小写开头,如果字符串x = "Alpha_Beta_Gamma"那么它应该打印字符串是符合的
采纳答案by Jochen Ritzel
Maybe you want str.istitle
也许你想要 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
回答by NullUserException
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
如在键盘上看到的
回答by Cristian Ciupitu
To test that all words start with an upper case use this:
要测试所有单词是否以大写开头,请使用以下命令:
print all(word[0].isupper() for word in words)
回答by inspectorG4dget
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"
回答by Rafael Sierra
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
这样你就知道是否有效以及哪个词是错误的
回答by Drew Nichols
Use list(str) to break into chars then import string and use string.ascii_uppercase to compare against.
使用 list(str) 分解成字符,然后导入 string 并使用 string.ascii_uppercase 进行比较。
Check the string module: http://docs.python.org/library/string.html
回答by mihoff
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
所以你可以把它写成 1 个字符串

