To check if a variable contains a value that is a string, use the isinstance
built-in function.
The isinstance
function takes two arguments. The first is your variable. Thesecond is the type you want to check for.
Example
Here is an example of using isinstance
:
>>> var = "a string">>> isinstance(var, str)True
Alternative approach
You can also use the type
built-in function to see if the type of yourvariable is str
. For example:
>>> type(var)<type 'str'>>>> type(var) == strTrue
So you could write something like this:
if type(var) == str: print("it's a string!")
Check if a string is a valid number
If you want to see if your variable can be converted to a number, refer tothis post.
Improve your Python skills fast
The fastest way to learn programming is with lots of practice. Learn a programmingconcept, then write code to test your understanding and make it stick. Try our onlineinteractive Python course today—it's free!
Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE thisweek only!