In Python, you can check if the type of a variable is a string using the built-in isinstance()
function. This function checks whether an object is an instance of a specific class or a subclass thereof.
Syntax:
isinstance(variable, str)
variable
: The variable you want to check.str
: The type you are checking for, in this case, thestr
type (which represents strings in Python).
Example:
# Example variables
var1 = "Hello, World!"
var2 = 123
var3 = 45.6
# Check if the variable is a string
print(isinstance(var1, str)) # Output: True
print(isinstance(var2, str)) # Output: False
print(isinstance(var3, str)) # Output: False
Explanation:
isinstance(var1, str)
returnsTrue
becausevar1
is a string.isinstance(var2, str)
andisinstance(var3, str)
returnFalse
becausevar2
is an integer andvar3
is a float, not strings.
Alternative Using type()
Another method is to use the type()
function, but it’s generally recommended to use isinstance()
because it handles inheritance and subclasses better.
# Check if variable is of type string using type()
print(type(var1) == str) # Output: True
However, isinstance()
is more flexible and preferred in most cases.