Both Python versions 2 and 3 provide several helpful string methods that let you find the string’s contents. Here’s how to use them.
The functions in this article are useful if you want to validate user input – for example, you may want to check that a user-inputted string is a valid number before converting it to a number variable to prevent errors and warn the user that they need to try again.
isdigit() and isalpha() are commonly used methods to identify a string’s contents, but there are several others built-in to Python, which will also be explored.
These string methods can be called on any string in Python like so:
myString = "Hello Python" myString.isdigit() # Will return False
Python 2 & 3
The following methods all work in both Python versions 2 and 3, and all return either True or False values:
True if all characters in the string are alphanumeric and the string is not empty
True if all characters in the string are alphabetic and the string is not empty
True if all characters in the string are digits and the string is not empty
True if all characters in the string are lowercase and the string s not empty
True if there is only whitespace (spaces, tabs, etc.) in the string and the string is not empty
True if all of the words in the string are capitalized, and the string is not empty
True if all of the characters in the string are UPPERCASE and the string is not empty
Python 3 provides some additional methods to check the contents of a string:
True if all characters are decimal characters (0-9, periods), and the string is not empty
True if the string is a valid identifier. An identifier is the name of a class, function, or variable
True if all characters in the string are numeric, and the string is not empty
True, if all the string characters are printable, this includes spaces but excludes other non-printable characters. The string also cannot be empty
For more information about string functions, and information about locales, check out the official docs for your version of Python at:
Here are some examples of the above methods in use:
myString = "Hello Python" numString = "12345" whiteString = " " idString = "myString" myString.isnumeric() # False myString.isprintable() # True numString.isdigits() # True whiteString.isspace() # True numString.isidentifier() # False idSString.isidentifier() # True (as there is a variable with that name)
These methods can all be used with Python Boolean Logic to control your application’s flow based on the contents of strings.
Check out our other Python string articles: