How to check if a string contains only upper case letters in Python?

PythonServer Side ProgrammingProgramming

We can check if a string contains only upper case letters using 2 methods. First is using method isupper(). 

example

print( 'Hello world'.isupper())
print('HELLO'.isupper())

Output

False
True

You can also use regexes for the same result. For matching only uppercase, we can call the re.match(regex, string) using the regex: "^[A-Z]+$". 

example

import re
print(bool(re.match('^[A-Z]+$', '123aAbc'))
print(bool(re.match('^[A-Z]+$', 'ABC'))

Output

False
True
raja
Published on 08-Dec-2017 15:50:51
Advertisements