How to Check If a Variable Is a String in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a variable is a string in Python. This involves understanding the fundamental string data type and exploring methods to identify strings.

You'll begin by creating and manipulating strings using single, double, and triple quotes, including multi-line strings. Then, you'll learn to use the type() function and the isinstance() function to confirm whether a variable holds a string value.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("Classes and Objects") subgraph Lab Skills python/variables_data_types -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} python/numeric_types -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} python/strings -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} python/booleans -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} python/build_in_functions -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} python/classes_objects -.-> lab-559603{{"How to Check If a Variable Is a String in Python"}} end

Understand Strings in Python

In this step, you'll learn about strings in Python. Strings are used to represent text, and they are one of the most fundamental data types in programming. You'll explore how to create strings, how to work with them, and some of the common operations you can perform on strings.

First, let's create a Python file named string_examples.py in your ~/project directory using the VS Code editor.

Strings can be created using single quotes ('...') or double quotes ("..."). Let's add some examples to string_examples.py:

## Creating strings
string1 = 'Hello, LabEx!'
string2 = "Python is fun"

print(string1)
print(string2)

Save the file. Now, let's run this script using the python command in the terminal:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun

Strings can also contain numbers, symbols, and spaces:

string3 = "12345"
string4 = "!@#$%^"
string5 = "This is a sentence."

print(string3)
print(string4)
print(string5)

Add these lines to your string_examples.py file and run it again:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.

Python also supports multi-line strings using triple quotes ('''...''' or """..."""):

string6 = '''This is a
multi-line string.'''

string7 = """This is another
multi-line string."""

print(string6)
print(string7)

Add these lines to your string_examples.py file and run it again:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.

Understanding how to create and use strings is essential for working with text data in Python. In the next steps, you'll learn more about string operations and how to manipulate strings effectively.

Use type() to Check

In this step, you'll learn how to use the type() function in Python to check the data type of a variable. This is a useful tool for understanding the kind of data you're working with and for debugging your code.

Let's continue using the string_examples.py file you created in the previous step. We'll add some code to check the types of the variables we defined.

The type() function returns the type of an object. For example, if you have a string variable, type() will return <class 'str'>.

Add the following lines to your string_examples.py file:

## Checking the type of variables
print(type(string1))
print(type(string2))
print(type(string3))

Save the file. Now, let's run the script using the python command in the terminal:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>

As you can see, the type() function confirms that string1, string2, and string3 are all of type str, which stands for string.

Now, let's add some other types of variables to see how type() works with them. Add the following lines to your string_examples.py file:

## Checking the type of other variables
number = 10
decimal = 3.14
boolean = True

print(type(number))
print(type(decimal))
print(type(boolean))

Save the file and run it again:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Here, type() shows that number is an int (integer), decimal is a float (floating-point number), and boolean is a bool (boolean).

Using type() is a simple way to check the data type of a variable in Python. This can be helpful when you're working with different types of data and need to ensure that you're performing the correct operations.

Confirm with isinstance()

In this step, you'll learn how to use the isinstance() function in Python to check if an object is an instance of a particular class or type. This is another way to verify the data type of a variable, and it can be especially useful when working with inheritance and custom classes.

Let's continue using the string_examples.py file you've been working with. We'll add some code to demonstrate how isinstance() works.

The isinstance() function takes two arguments: the object you want to check and the class or type you want to check against. It returns True if the object is an instance of the specified class or type, and False otherwise.

Add the following lines to your string_examples.py file:

## Checking with isinstance()
print(isinstance(string1, str))
print(isinstance(number, int))
print(isinstance(decimal, float))
print(isinstance(boolean, bool))
print(isinstance(string1, int))

Save the file. Now, let's run the script using the python command in the terminal:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False

As you can see, isinstance(string1, str) returns True because string1 is a string. Similarly, isinstance(number, int) returns True because number is an integer, and so on. However, isinstance(string1, int) returns False because string1 is not an integer.

isinstance() can also be used with custom classes. For example:

class MyClass:
    pass

obj = MyClass()

print(isinstance(obj, MyClass))

Add these lines to your string_examples.py file and run it again:

python ~/project/string_examples.py

You should see the following output:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False
True

Here, isinstance(obj, MyClass) returns True because obj is an instance of MyClass.

Using isinstance() is a powerful way to check the type of an object in Python, especially when working with inheritance and custom classes. It allows you to write more robust and flexible code that can handle different types of data correctly.

Summary

In this lab, the initial step focuses on understanding strings in Python, a fundamental data type for representing text. It covers creating strings using single quotes, double quotes, and triple quotes for multi-line strings. Examples are provided to demonstrate how strings can contain numbers, symbols, and spaces.

The lab guides users to create a string_examples.py file, add various string examples, and execute the script using the python command to observe the output. This hands-on approach reinforces the understanding of string creation and manipulation in Python.