In this article, you’ll learn how to convert strings of Python types to concrete Python types. The ability to convert strings to different Python types is important if you’re reading data from a file or relying on user input. We’ll walk you through the following methods for converting strings to Python types:

  • Converting Strings to integers
  • Converting Complex String Representations to Python Types
    • Using Custom Code
    • Using json.loads() method
    • Using ast.literal_eval() method

Converting Strings to Integers

In the next few sections you’ll see how string representation of complex Python types can be converted to concrete Python types, but before we do that, let’s look at a simple example of how you can convert strings of integers to actual integer types.

The following script defines a string variable that stores an intege, 58, in a string format. The value and the type of the string variable is printed using the type() function. You can see that the variable type is str, meaning it’s a string.

num = "58"

print(num)

print(type(num))

Output:

58

<class 'str'>

To convert a string to an integer, you need to pass the string to the int() function, as shown in the following example.

num2 = int(num)

print(type(num2))

Output:

<class 'int'>

The int() function throws an exception if you pass it a string of something other than an integer. Here’s an example.

num = "hello"

num2 = int(num)

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [3], in <cell line: 2>()
      1 num = "hello"
----> 2 num2 = int(num)

ValueError: invalid literal for int() with base 10: 'hello'

Converting Complex String Representations to Python types

Let’s see to convert string representations of more complex Python types to concrete Python types.

Converting Strings to Python Types via Custom Code

You can write a custom piece of code to convert string representations of Python types into concrete Python type. However, it can be rather cumbersome. Let’s demonstrate this with the help of an example.

The following script defines string representation of a Python list. If you check its type, you will see that its a string.

colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']"

print(type(colors))

Output:

<class 'str'>

To convert the string representation of the above list into a Python type, you need to do some string parsing.

As a first step, you can remove leading and trailing square brackets and remove the quotes surrounding the individual list items. Here’s one way to do this:

temp = colors.strip('[]').replace("'", "")

print(temp)

print(type(temp))

Output:

Orange, Green, Yellow, Blue, Red
<class 'str'>

Next, you can use the Python split() function to split the string using commas. The split() function returns the list of items, as shown in the following script.

colors_list = temp.split(', ')

print(colors_list)

print(type(colors_list))

Output:

['Orange', 'Green', 'Yellow', 'Blue', 'Red']

<class 'list'>

The following script combines the above steps in single line of code.

colors_list = colors.strip('[]').replace("'", "").split(", ")

print(colors_list)

print(type(colors_list))

Output:

['Orange', 'Green', 'Yellow', 'Blue', 'Red']

<class 'list'>

You can see that converting a string representation of a Python type to a concrete Python type, like a list, can be time-consuming and it can only be used for specific string formats. You’d have to write a different code for every Python type.

Fortunately, there are easier ways to convert strings to Python types. We’ll go over these methods in the next couple sections.


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

Converting Strings to Python Types using json.loads()

You can use the loads() function from the Python json module to convert a string to a Python type.

However, it’s important that the string representation of a Python type comply with the JSON format.

For example, the following script will throw an exception since the list items are enclosed in single quotations, whereas the JSON expects list items to be enclosed in double quotations. For that reason, a basic familiarity with JSON is required when using the json.loads() function.

import json

colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']"

colors_list = json.loads(colors)

print(colors_list)

print(type(colors_list))

Output:

JSONDecodeError: Expecting value: line 1 column 2 (char 1)

In the following script, the items in the colors list are enclosed in double quotes, so the json.loads() function will successfully convert the string representation of the list to an actual Python list.

colors = '["Orange", "Green", "Yellow", "Blue", "Red"]'

import json

colors_list = json.loads(colors)

print(colors_list)

print(type(colors_list))

Output:

['Orange', 'Green', 'Yellow', 'Blue', 'Red']

<class 'list'>

Converting Strings to Python Types using ast.literal_eval()

Finally, you can use the literal_eval() function from the Python ast (Abstract Syntax Trees) module to convert a string to a Python type.

The literal_eval() function is, by far, the safest option for converting a string to a Python type since it can convert string representations of Python types in a variety of formats.

For example, the following script converts a string representation of a Python list with items enclosed in single quotes to a concrete Python list.

import ast

colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']"

colors_list = ast.literal_eval(colors)
print(colors_list)
print(type(colors_list))

Output:

['Orange', 'Green', 'Yellow', 'Blue', 'Red']

<class 'list'>

In the same way, you can convert a string representation of a Python list with double quotes, as shown below:

colors = '["Orange", "Green", "Yellow", "Blue", "Red"]'

colors_list = ast.literal_eval(colors)

print(colors_list)

print(type(colors_list))

Output:

['Orange', 'Green', 'Yellow', 'Blue', 'Red']

<class 'list'>

As a final example, our next script demonstrates how you can convert a string representation of a Python dictionary to an actual Python dictionary using the literal_eval() function.

scores = "{'James':10, 'John':35, 'Sara':40}"

scores_dict = ast.literal_eval(scores)

print(scores_dict)

print(type(scores_dict))

Output:

{'James': 10, 'John': 35, 'Sara': 40}

<class 'dict'>

The string was successfully converted to a dictionary, with the keys being stored as strings and the values being stored as integers. Hopefully this example helped illustrate just how powerful the literal_eval() function is!


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit