How to Check if the Value of a variable is a String in Python

check if the value of a variable is an string

Picture of Nsikak Imoh, author of Macsika Blog
Plain background with the text How to Check if the Value of a variable is a String in Python
Plain background with the text How to Check if the Value of a variable is a String in Python

Table of Content

Sometimes, when you write a Python program, you might want to check if the value of a variable is a String.

You can check if the value of a variable is a string by either using Python’s builtin type() function by passing the variable as an argument, and then compare the result or using the isinstance() function by passing the two arguments: the variable, and the str class.

How to use the type() Function to Check if the Value of a Variable is a String in Python

Here’s a code example on how to check if the value of a variable is a string using Python’s builtin type():

greeting = "Hello, World!"
type(greeting) == str #True
Highlighted code sample.

How to use the isinstance() Function to Check if the Value of a Variable is a String in Python

Here’s a code example on how to check if the value of a variable is a string using Python’s builtin isinstance():

greeting = "Hello, World!"
isinstance(greeting, str) #True
Highlighted code sample.

Wrap Off

That’s a candid example of how you can check if the value of a variable is a string by either using Python’s builtin type() function or builtin isinstance() function.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Get the Complete Code of Python Code Snippets on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?