To check if a variable contains a value that is a string, use the
isinstance function takes two arguments. The first is your variable. The
second is the type you want to check for.
Here is an example of using
>>> var = "a string" >>> isinstance(var, str) True
You can also use the
type built-in function to see if the type of your
str. For example:
>>> type(var) <type 'str'> >>> type(var) == str True
So you could write something like this:
if type(var) == str: print("it's a string!")
If you want to see if your variable can be converted to a number, refer to this post.
Try our practical beginner lessons, or test your skills with our challenges.