Characters (digits, letters and symbols such as $, @, % and *) are the fundamental building blocks of programs. Every program is composed of characters that, when grouped meaningfully, represent instructions and data that the interpreter uses to perform tasks. Many programming languages have separate string and character types. In Python, a character is simply a one-character string.
Python provides string methods for testing whether a string matches certain characteristics. For example, string method isdigit
returns True
if the string on which you call the method contains only the digit characters (0
–9
). You might use this when validating user input that must contain only digits:
In [1]: '-27'.isdigit()
Out[1]: False
In [2]: '27'.isdigit()
Out[2]: True
and the string method isalnum
returns True
if the string on which you call the method is alphanumeric—that is, it contains only digits and letters:
In [3]: 'A9876'.isalnum()
Out[3]: True
In [4]: '123 Main Street'.isalnum()
Out[4]: False
The table below shows many of the character-testing methods. Each method returns False
if the condition described is not satisfied:
(Fill-In) Method returns True
if a string contains only letters and numbers.
Answer: isalnum
.
(Fill-In) Method returns True
if a string contains only letters.
Answer: isalpha
.