19

Given any string in Python, how can I test to see if its first letter is a capital letter? For example, given these strings:

January
dog
bread
Linux
table

I want to be able to determine that January, and Linux are capitalized.

mix
  • 6,943
  • 15
  • 61
  • 90

3 Answers3

34
In [48]: x = 'Linux'
In [49]: x[0].isupper()
Out[49]: True
In [51]: x = 'lINUX'
In [53]: x[0].isupper()
Out[53]: False
KillianDS
  • 16,936
  • 4
  • 61
  • 70
13

You can use something nice:

string = "Yes"
word.istitle() # -> True

but note that str.istitle looks whether every word in the string is title-cased! so it will only work on on 1 string in your case :)

"Yes no".istitle() # -> False!

If you just want to check the very first character of a string use KillianDS Answer...

Kobi K
  • 7,743
  • 6
  • 42
  • 86
  • 3
    istitle() checks if the string follows the format (uppercase+sequence of lowercase characters), so for example if testing "YeS" this will return "false" although first character is uppercase, best option is to use .upper() method – A.Midany Dec 26 '17 at 16:20
2
if(x[0].isupper()):
       return True
elif(x[0].islower()):
       return False
kotAPI
  • 1,073
  • 2
  • 13
  • 37
  • 2
    Or you can drop the if statement and just: return x[0].isupper() Every time you have in if statement in your code that ends with returning True, else False (or vice versa), it can most likely be compressed into returning the logical operation from the if statement. – Radek Nov 21 '18 at 15:34