How To Convert String To Object In Python

Objects are instances of a class that has methods and attributes associated with it in Python and the string is a commonly used data type for representing text. Based on the uses of different circumstances, It is important to convert a string to an object in Python. This action is typically performed when we want to do an operation on the data stored in the string.

During the conversion of a string into an object, we can access these methods and attributes which perform operations on the data.

Why is there a need to convert String to object?

Here are a few reasons to change string to object in Python:

  • Generally, we receive the data in the form of a string from a user. To acquire the result, we require it to convert it to a relevant data type.
  • By converting a string to an object, we can leverage these functions and modules to implement complex operations on the data.
  • For Complex data structures, objects are more reliable as compared to strings because by using objects we can save memory as well as increase performance.
  • Python objects can be used to perform such operations which are not handled strings, such as arithmetic operations, comparisons, or boolean logic.
  • During data transmission, it passes through different parts of an application or between different applications.

In this article, we will examine some essential techniques for changing the string to an object in Python.

How to change string to object in Python

There are six different ways to convert string to object in Python which we are discussing here with detailed explanations about the approach, code, and output for each method.

The Methods are:-

  1. By the use of the Eval() function
  2. By the use of a custom function
  3. By using the CSV module
  4. By using ast.literal_eval() function
  5. By Using json.load() function
  6. By using regular expression and string method

Approach 1: By the use of the Eval() function

The Eval() function can evaluate a string that contains a Python expression such as an arithmetic operation, function call, and variable reference. In some cases It is powerful but also It can be risky if the input string is not trustable because it can execute arbitrary code.

The example of using the Eval( ) function with explanation:

Input:

str_obj = "[9,8,1]"
lst_obj = eval(str_obj)
print(lst_obj)

Output:

[9, 8, 1]

Explanation:

  • Here the string object passes through the eval() function and it returns the same data types as the equivalent object.
  • In this code, the string object “[9, 8, 1]” is handed to the eval() function which produces a list object [9, 8, 1].

Approach 2: By the use of a custom function

This method parses and converts the input string into an object by using specific rules and operations. It can be more secure and customizable than the eval()  function, but It may require some testing and coding.

An example of using a custom function with explanation:

Input:

def convert_to_dict(str_obj):
    dict_obj = {}
    for item in str_obj.split(','):
        key, value = item.split(':')
        dict_obj[key.strip()] = value.strip()
    return dict_obj

str_obj = "{'name': 'Rupam', 'age': 20, 'city': 'New Delhi'}"
dict_obj = convert_to_dict(str_obj)
print(dict_obj)

Output:

{"{'name'": "'Rupam'", "'age'": '20', "'city'": "'New Delhi'}"}

Explanation:

  • Custom function ‘convert_to_dict’ takes a string input and initializes an empty dictionary object.
  • The input string is split by a comma to generate a list of key-value pairs.
  • Each key-value pair is looped through and split by a colon to extract the key and value.
  • Leading and trailing whitespaces are removed from the key and value.
  • Key-value pairs are added to the dictionary object using dict_obj[key.strip()] = value.strip() syntax.
  • The resulting dictionary object is returned and assigned to the variable dict_obj.
  • The output is printed as {“{‘name'”: “‘Rupam'”, “‘age'”: ’20’, “‘city'”: “‘New Delhi’}”} after running the function.

Note that the age value is a string, not an integer as in this approach.

Approach 3: By using the CSV module

The CSV module provides functions for parsing and writing CSV data for converting a  string with comma-separated values into a list of dictionaries or lists. It can handle various formats but there are some requirements in terms of input string as a valid CSV file.

An example of using the CSV module with explanation:

Input:

import csv
string = "name,age,city\nRocky,26,Kolkata\nMary,25,New Delhi"
rows = csv.reader(string.splitlines())
list_obj = [row for row in rows]
print(list_obj)

Output:

[['name', 'age', 'city'], [Rocky', '26', 'Kolkata'], ['Mary', '25', 'New Delhi']]

Explanation:

  • The CSV module is imported using ‘import csv’.
  • The string object is split into a list of rows using the splitlines() method based on the newline character \n.
  • The csv.reader() function is used to read the scopes of a CSV file or string. It accepts a list of rows as input, which denotes the CSV data and produces a reader object that can be used to repeat over the rows and access the values in each cell of the CSV data.
  • A list comprehension is used to store a list of values for each row in the new list object.
  • The resulting list object is printed to the console using the print() function.

Approach 4: By using ast.literal_eval() function

This approach evaluates a string as a Python literal expression and it returns the result as an object. It can handle various literal data types and data structures and there is an advantage of this method. It is safer than the eval() function because it only allows a restricted set of operations.

An example of using ast.literal_eval() function with explanation:

Input:

import ast
str = "[1, 2, 3, [4, 5, 6], {'a': 'A', 'b': 'B'}, True, None]"
list_obj = ast.literal_eval(str)
print(list_obj)

Output:

[1, 2, 3, [4, 5, 6], {'a': 'A', 'b': 'B'}, True, None]

Explanation:

  • The ast module is imported using ‘import ast’.
  • The input string contains a list with different data types.
  • The ast.literal_eval() function evaluates the string as a Python expression and returns the corresponding Python object.
  • In this case, the string is evaluated as a list object with different data types.
  • The resulting Python object is assigned to the variable list_obj.

Approach 5: By using json.load () function

In this approach, we use the JSON module which provides functions for parsing and writing JSON data for converting a string with JSON format into a Python object. The JSON method can handle different JSON data types and data structures but there is a requirement for the input string in JSON format.

An example of JSON.load() function with explanation:

Input:

import json
string = '{"name": "Ritesh", "age": 30, "city": "Noida"}'
dict_obj = json.loads(string)
print(dict_obj)

Output:

{'name': 'Ritesh', 'age': 30, 'city': 'Noida'}

Explanation:

  • The string contains JSON data that can be turned into a Python object (here a dictionary) by using the json.loads() function. The resulting object is assigned to the variable dict_obj.
  • The resulting Python object is printed.
  • The input string is in JSON format, enclosed within {} brackets, and with key-value pairs separated by :
  • The json.loads() function accepts the string as input and produces a Python dictionary, which is assigned to the variable dict_obj.
  • The resulting Python dictionary can be used in the rest of the code as a regular dictionary.

Approach 6: By using regular expression and string method

By using a regular expression, we can extract the desirable values from the string as an object. This method is applicable when a string has a specific pattern that can be matched using regex.

An example of regular expression and string method with explanation:

Input:

import re

string = "name=John;age=30;city=New York"
pattern = r"name=(.*?);age=(.*?);city=(.*)"
match = re.match(pattern, string)
dict_obj = {
    "name": match.group(1),
    "age": int(match.group(2)),
    "city": match.group(3)
}
print(dict_obj)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

Explanation:

  • The re module is imported using ‘import re’ to work with regular expressions.
  • The string to be converted is assigned to the string variable.
  • A regular expression pattern is defined that matches the desired values in the string. The pattern uses capturing groups to extract the values of name, age, and city.
  • The re.match() function is used to search the pattern in the string..
  • A dictionary object is created and the captured values are assigned to the corresponding keys in the dictionary. The age value is converted to an integer using the int() function.

This approach can be extended to handle more complex string patterns using more sophisticated regular expressions.

Best Approach of How to Convert String to Object in Python

There are several causes why using the CSV approach is often considered the best approach:

  • Simplicity: The CSV approach is straightforward and easy to understand.
  • Versatility: The CSV approach is adaptable and can be used for a broad range of data formats.
  • Efficiency: The CSV approach is generally more efficient than other approaches that involve more complex parsing or serialization of data.
  • Memory efficiency: The CSV approach is memory efficient because it involves reading the file line by line and converting each row to an object, rather than loading the entire file into memory at once.
  • Widespread usage: The CSV approach is widely used and supported by many programming languages and frameworks.

Sample problem for How to Convert str to object in Python for each of the approaches:

By the use of the Eval() function

Sample Problem 1:

you have a list of tuples containing the details of customers, where each tuple contains the name, age, and balance of a customer in the form of strings. You want to convert these tuples to dictionary objects, where the keys are the names of the customers, and the values are dictionaries containing their ages and balance as integers.

input

customer_list = [(‘Amar’, ’25’, ‘1000’), (‘Bhim’, ’30’, ‘2000’), (‘Shranik’, ’35’, ‘500’)]

Solution:

  • Initialize an empty dictionary to store the result.
  • Iterate over each tuple in the input list.
  • Extract the name, age, and balance of the customer from the tuple.
  • Convert the age and balance strings to integers using the int() function.
  • Create a dictionary object for the current customer, with their age and balance as values.
  • Add the customer dictionary to the result dictionary with their name as the key.
  • Return the result dictionary.

Input:

#input from the user
customer_list = [('Amar', '25', '1000'), ('Bhim', '30', '2000'), ('Shranik', '35', '500')]

# create an empty dictionary to hold the result
customer_dict = {}

# iterate over each tuple in the list
for name, age_str, balance_str in customer_list:

    # convert age and balance strings to integers
    age = int(age_str)
    balance = int(balance_str)

    # create a dictionary object for the current customer
    customer_dict[name] = {'age': age, 'balance': balance}

print(customer_dict)

 Output:

{'Amar': {'age': 25, 'balance': 1000}, 'Bhim': {'age': 30, 'balance': 2000}, 'Shranik': {'age': 35, 'balance': 500}}

By the use of a custom function

Sample Problem 2:

You want to transform a configuration file that has settings for your application in a string format into a dictionary object for more processing.

sample input

config = “{‘database’: {‘host’: ‘localhost’, ‘port’: 5432, ‘username’: ‘admin’, ‘password’: ‘secret’}, ‘logging’: {‘level’: ‘debug’, ‘file’: ‘app.log’}}”

Solution:

  • A string variable config is defined, which contains a nested dictionary in string format.
  • The json library is imported to parse the JSON string.
  • A function parse_config is defined that takes a string argument config_str.
  • The parse_config function replaces all the single quotes in the input string with double quotes to ensure valid JSON syntax.
  • The json.loads() method is utilized to transform the JSON string to a Python dictionary object.
  • The resulting dictionary object is returned by the parse_config function.
  • The config variable is passed to the parse_config function that returns a dictionary which is stored in the config_dict variable.
  • In the end, the config_dict dictionary is printed, which contains the same nested dictionary as the config variable.

Input:

#sample input you can take your own

config = "{'database': {'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret'}, 'logging': {'level': 'debug', 'file': 'app.log'}}"

# ------------solution --------------
import json
def parse_config(config_str):
    # Convert single quotes to double quotes for valid JSON syntax
    config_json = config_str.replace("'", "\"")
    # Load JSON string to Python dictionary
    config_dict = json.loads(config_json)
    return config_dict

config_dict = parse_config(config)
print(config_dict)

Output:

{'database': {'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret'}, 'logging': {'level': 'debug', 'file': 'app.log'}}

By using the CSV module

Sample Problem 3:

You have a CSV string that contains details of customers in the following format: name, age, and email. You want to convert this CSV string into a list of dictionaries where each dictionary represents a customer with keys for name, age, and email.

Solution:

  • First, import the CSV module.
  • Define the CSV string containing the customer details.
  • Convert the CSV string into a list of rows using the splitlines() method.
  • Initialize an empty list to store the dictionaries representing the customers.
  • Use the csv.DictReader() function to transform each row in the CSV list into a dictionary and loop through them.
  • Append the resulting dictionary to the list of customer dictionaries.
  • The final list of dictionaries represents the customers with keys for name, age, and email

Input:

import csv

csv_string = "Arpita,25,[email protected]\nPriya,30,[email protected]\nBabita,28,[email protected]"

csv_list = csv_string.splitlines()
customer_list = []
for row in csv_list:
    reader = csv.DictReader([row], fieldnames=['name', 'age', 'email'])
    customer_dict = next(reader)
    customer_list.append(customer_dict)

print(customer_list)

 Output:

[{'name': 'Arpita', 'age': '25', 'email': '[email protected]'}, {'name': 'Priya', 'age': '30', 'email': '[email protected]'}, {'name': 'Babita', 'age': '28', 'email': '[email protected]'}]

By using ast.literal_eval() function

Sample Problem 4:

You have a string which represents a Python object such as a list or a dictionary, and you need to convert it back to the original object type in Python.

Solution:

  • Import the ast module which provides a safe way to evaluate strings containing Python expressions.
  • Use the ast.literal_eval() function to evaluate the string and convert it back to the original object type.
  • The literal_eval() function evaluates the expression in a restricted mode, so it’s safe to use with untrusted input.
  • The input string must be a valid Python expression if not then a ValueError will be raised.
  • The output of literal_eval() will be a Python object that represents the input string.

Input:

import ast

# String representing a dictionary
dict_str = "{'name': 'John', 'age': 30, 'city': 'New York'}"

# Convert string to a dictionary object
dict_obj = ast.literal_eval(dict_str)

print(type(dict_obj))
print(dict_obj)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'} nb

By Using json.load() function

Sample Problem 5:

You have a JSON-formatted string that represents a dictionary containing information about a single book. You need to convert this string to a Python object so you can extract and analyze the book data.

Solution:

  • Store the JSON-formatted string as a variable.
  • Use the json.loads() function to convert the string to a Python object (in this case, a dictionary).
  • Access the values in the dictionary to extract the book data as needed.

Input:

import json

# JSON-formatted string representing book data
book_json = '{"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960, "publisher": "J. B. Lippincott & Co.", "genres": ["Fiction", "Southern Gothic"]}'

# Convert JSON string to Python object
book_data = json.loads(book_json)

# Extract and output book data
print(f'Title: {book_data["title"]}')
print(f'Author: {book_data["author"]}')
print(f'Year: {book_data["year"]}')
print(f'Publisher: {book_data["publisher"]}')
print(f'Genres: {", ".join(book_data["genres"])}')

Output:

Title: To Kill a Mockingbird
Author: Harper Lee
Year: 1960
Publisher: J. B. Lippincott & Co.
Genres: Fiction, Southern Gothic

By using regular expression and string method

Sample Problem 6:

You have a string that holds information about a person’s name, age, and email address separated by commas. You want to extract this information and create an object with these attributes as keys.

Example string: “Rishav Singh, 25,[email protected]

Solution:

  • Use the split() method to split the string into a list of its three components: name, age, and email.
  • Use regular expressions to validate the age and email components.
  • Create a dictionary object with the name, age, and email as keys and the corresponding values as values.
  • Return the dictionary object.

Input:

import re

def parse_info(info_str):
    # Split the string into a list of name, age, and email
    info_list = info_str.split(", ")
    
    # Validate the age
    if not re.match(r'^\d+$', info_list[1]):
        raise ValueError("Invalid age format")
    
    # Validate the email
    if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', info_list[2]):
        raise ValueError("Invalid email format")
    
    # Create a dictionary object with the name, age, and email
    info_dict = {"name": info_list[0], "age": int(info_list[1]), "email": info_list[2]}
    
    return info_dict

# Test the function with the example string
info_str = "Rishav Singh, 25, [email protected]"
info_dict = parse_info(info_str)
print(info_dict)

Output:

{'name': 'Rishav Singh', 'age': 25, 'email': '[email protected]'}

Conclusion

We have discussed various methods to transform strings into objects. Each method has its benefits and drawbacks. Picking the right method depends on the specific uses and data being processed. It is important to ensure data privacy and security when dealing with untrusted data.

Based on their pros and cons, Using the CSV module can be considered the best approach to convert strings into objects. Users can choose the best approach for their specific requirements.