Since Python does not support static type checking (i.e type checking at compile type), if you ever want to check if a Python variable or object is a String or not; we need to use certain methods.
Let us understand some of the ways of checking for a string type object.
1. Using isinstance() method
The isinstance(object, type) method checks if
object belongs to
type, and returns True if that condition holds, and False otherwise.
Common types are: int, str, list, object, etc.
Since we want to check for
str type, we will use
isinstance(object, str) and check if it is
Let us understand this through an example.
a = 123 b = 'Hello' print('Is a an instance of str?', isinstance(a, str)) print('Is b an instance of str?', isinstance(b, str))
Is a an instance of str? False Is b an instance of str? True
2. Using type(object) method
This is similar to the
isinstance() method, but this explicitly returns the type of the object.
Let us use this to check if the returned type is
str or not.
a = 123 b = 'Hello' print('type(a) =', type(a)) print('type(b) =', type(b)) print('Is a of type string?', type(a) == str) print('Is b of type string?', type(b) == str)
type(a) = <class 'int'> type(b) = <class 'str'> Is a of type string? False Is b of type string? True
Check if Function parameter is a String
We can apply any one of the above methods to introduce a ‘check’ condition in any function, which allows us to execute the main body of the function only if the input is a string.
Let us understand this using a simple example.
a = 123 b = 'Hello' def capitalize_name(inp): # We can also use "if isinstance(inp, str)" if type(inp) != str: print('Input must be a string') else: print(inp.upper()) capitalize_name(a) capitalize_name(b)
Input must be a string HELLO
Our function now explicitly checks if the parameter is a string, before proceeding to the main body. These type checks can potentially avoid unnecessary run-time errors due to Python’s dynamic type checking.
We are not throwing any errors from our function. But, in real life programming, most of these function parameter type validations throw
In this article, we learned about how we could use Python’s
type() methods and check if the input is a string or not. We also applied this to a function to only accept a parameter if it is a string.
Now, there are potentially much lesser errors that could be caused during run-time, and this format is very essential for a good Python program. Hope you found this post useful!