How to Check If type of a Variable is String in Python

Itacen Sabacok | Sep 30, 2022

We can use isinstance() function to check that. here is the example below;

1from datetime import datetime
2
3now = datetime.now()      # now is a datetime object
4year = now.strftime("%Y") # year is a string
5
6print("is now variable string?  {}".format(isinstance(now, str)))
7print("is year variable string? {}".format(isinstance(year, str)))

OUTPUT:

is now variable string? False

is year variable string? True