在Python中,如何测试任意字符串的第一个字母是否为大写?例如,给定以下字符串:
January
dog
bread
Linux
table
我希望能够确定January
和Linux
是大写字母。
In [48]: x = 'Linux'
In [49]: x[0].isupper()
Out[49]: True
In [51]: x = 'lINUX'
In [53]: x[0].isupper()
Out[53]: False
你可以使用某些好用的东西:
string = "Yes"
word.istitle() # -> True
但请注意,str.istitle检查字符串中的每个单词是否为标题格式!因此,在你的情况下,它只适用于一个字符串 :)
"Yes no".istitle() # -> False!
如果您只想检查字符串的第一个字符,请使用KillianDS的答案...
if(x[0].isupper()):
return True
elif(x[0].islower()):
return False