如何测试字符串是否以大写字母开头?

mix*_*mix 7 python string

给定Python中的任何字符串,我如何测试它的第一个字母是否是大写字母?例如,给定这些字符串:

January
dog
bread
Linux
table
Run Code Online (Sandbox Code Playgroud)

我希望能够确定January并且Linux大写.

Kil*_*nDS 21

In [48]: x = 'Linux'
In [49]: x[0].isupper()
Out[49]: True
In [51]: x = 'lINUX'
In [53]: x[0].isupper()
Out[53]: False
Run Code Online (Sandbox Code Playgroud)


Kob*_*i K 6

您可以使用一些不错的东西:

string = "Yes"
word.istitle() # -> True
Run Code Online (Sandbox Code Playgroud)

但请注意,str.istitle看起来是否字符串中的每个单词都用大写字母区分大小写!因此在您的情况下,它将仅对1个字符串起作用:)

"Yes no".istitle() # -> False!
Run Code Online (Sandbox Code Playgroud)

如果只想检查字符串的第一个字符,请使用KillianDS Answer ...

  • istitle() 检查字符串是否遵循格式(大写+小写字符序列),因此,例如,如果测试“Yes”,这将返回“false”,尽管第一个字符是大写,最好的选择是使用 .upper() 方法 (3认同)