Python’s str
type also features a number of methods that can be used to evaluate the contents of a string. These are str.isalpha
, str.isdigit
, str.isalnum
, str.isspace
. Capitalization can be tested with str.isupper
, str.islower
and str.istitle
.
str.isalpha
str.isalpha
takes no arguments and returns True
if the all characters in a given string are alphabetic, for example:
>>> "Hello World".isalpha() # contains a space
False
>>> "Hello2World".isalpha() # contains a number
False
>>> "HelloWorld!".isalpha() # contains punctuation
False
>>> "HelloWorld".isalpha()
True
As an edge case, the empty string evaluates to False
when used with "".isalpha()
.
str.isupper
, str.islower
, str.istitle
These methods test the capitalization in a given string.
str.isupper
is a method that returns True
if all characters in a given string are uppercase and False
otherwise.
>>> "HeLLO WORLD".isupper()
False
>>> "HELLO WORLD".isupper()
True
>>> "".isupper()
False
Conversely, str.islower
is a method that returns True
if all characters in a given string are lowercase and False
otherwise.
>>> "Hello world".islower()
False
>>> "hello world".islower()
True
>>> "".islower()
False
str.istitle
returns True
if the given string is title cased; that is, every word begins with an uppercase character followed by lowercase characters.
>>> "hello world".istitle()
False
>>> "Hello world".istitle()
False
>>> "Hello World".istitle()
True
>>> "".istitle()
False
str.isdecimal
, str.isdigit
, str.isnumeric
str.isdecimal
returns whether the string is a sequence of decimal digits, suitable for representing a decimal number.
str.isdigit
includes digits not in a form suitable for representing a decimal number, such as superscript digits.
str.isnumeric
includes any number values, even if not digits, such as values outside the range 0-9.
isdecimal isdigit isnumeric
12345 True True True
១2߃໔5 True True True
①²³🄅₅ False True True
⑩⒓ False False True
Five False False False
Bytestrings (bytes
in Python 3, str
in Python 2), only support isdigit
, which only checks for basic ASCII digits.
As with str.isalpha
, the empty string evaluates to False
.