8.10 Characters and Character-Testing Methods

  • In Python, a character is simply a one-character string
  • Python provides string methods for testing whether a string matches certain characteristics
  • isdigit returns True if the string on which you call the method contains only the digit characters (09)
    • Useful for validating data
In [1]:
'-27'.isdigit()
Out[1]:
False
In [2]:
'27'.isdigit()
Out[2]:
True

8.10 Characters and Character-Testing Methods (cont.)

  • isalnum returns True if the string on which you call the method is alphanumeric (only digits and letters)
In [3]:
'A9876'.isalnum()
Out[3]:
True
In [4]:
'123 Main Street'.isalnum()
Out[4]:
False

8.10 Characters and Character-Testing Methods (cont.)

  • Table of many character-testing methods
String Method Description
isalnum() Returns True if the string contains only alphanumeric characters (i.e., digits and letters).
isalpha() Returns True if the string contains only alphabetic characters (i.e., letters).
isdecimal() Returns True if the string contains only decimal integer characters (that is, base 10 integers) and does not contain a + or - sign.
isdigit() Returns True if the string contains only digits (e.g., '0', '1', '2').
isidentifier() Returns True if the string represents a valid identifier.
islower() Returns True if all alphabetic characters in the string are lowercase characters (e.g., 'a', 'b', 'c').
isnumeric() Returns True if the characters in the string represent a numeric value without a + or - sign and without a decimal point.
isspace() Returns True if the string contains only whitespace characters.
istitle() Returns True if the first character of each word in the string is the only uppercase character in the word.
isupper() Returns True if all alphabetic characters in the string are uppercase characters (e.g., 'A', 'B', 'C').

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.