W3docs

How to check if type of a variable is string?

You can use the type() function in Python to check the type of a variable.

You can use the type() function in Python to check the type of a variable. Here is a code snippet that demonstrates how to check if a variable is a string:

Check the type of a Python variable using the type function

python— editable, runs on the server
Info

Watch a video course: Python - The Practical Guide

Alternatively, you can use the isinstance() function to check if a variable is an instance of a certain type. Here is an example:

Check the type of a Python variable using the isinstance function

python— editable, runs on the server

Note that type() returns a type object, so the boolean result comes from the comparison == str. isinstance() directly returns a boolean. In Python, isinstance() is generally preferred because it correctly handles inheritance.