There are two ways to check if a variable is a string in Python. First isinstance() method and second type() method.
How to check if a variable is a string in Python
Simple python examples code:
Using isinstance(var, str)
The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for. In our case, we are testing string type so the second parameter will be a string type.
var = "a string" print(isinstance(var, str))
Using type() – Alternative approach
You can also use the type built-in function to see if the type of your variable is str
var = "a string" print(type(var))
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.