Log In

String Conversion in Python

String Conversion in Python
11.12.2023
Reading time: 8 min
Hostman Team
Technical writer

Python is one of the most popular programming languages. It has many built-in methods and functions, including those for working with strings. 

Strings are data objects that store a sequence of characters, including letters, numbers, punctuation marks, etc. String conversion is necessary when the user cannot perform some operations on strings due to their peculiarities. For example, he cannot add two strings storing numbers and get their sum. For this purpose, it is necessary to perform the conversion first and then realize the addition. This principle works for all other data types as well.

This instruction will tell you how to convert strings to other data types.

String conversion

String conversion is the process of changing a string data type to another, implemented using Python's built-in methods. There are several cases when you might need it.

  • Information received from users

This may occur in some applications where the user, for example, fills out an input form. By default, all the specified information will be passed as a string. For further interaction with the data, you'll need to convert them to the correct type.

  • Information read from files.

In this case, the user, just as in the previous example, needs to transform the received sequence of characters, whether they are in JSON or XML files. 

  • Data from the database.

When interacting with the database, some data may also be interpreted into the program code as strings. You'll need to convert them to the appropriate data type for the code to work properly.

  • String Comparison.

If you need to compare two strings, they must be of the same data type. However, the choice of this type depends on the comparison requirements. For example, if you want to find out which of the numbers in the compared sequences are larger, you would convert strings into a numeric data format and then perform the comparison.

Based on the examples above, we can say that it is impossible to correctly perform the required operations in your code without converting strings. The Python built-in methods can help with the implementation of this process.

-

String → Integer

First, let's talk about converting a sequence of characters into numbers. The first method is int(). It allows you to convert a string to an integer in Python. Its syntax looks as follows:

int(example_string)

It takes an initial sequence of characters as an argument and then converts it to an integer.

Let's look at an example:

example_string = "112"
result = int(example_string)
print(result)

The result is shown in the picture below.

Image10

If a function argument contains not only digits but also letters or other characters, int() will not be able to perform the conversion and will generate a ValueError. However, in some cases, it can be bypassed. For example, the user passed a number in hexadecimal notation into the argument, which implies the presence of letters in this sequence. In this case, an additional argument is used that specifies the base of the number system. It will make it clear that it is indeed a number.

Let's look at this example:

example_string = "A1"
result = int(example_string, 16)
print(result)

The compiler will not generate any errors and will output the result shown in the image below.

Image4

We have successfully executed the code and the program has converted the string into a decimal integer 161.

String → Float Number

In this chapter, we will talk about converting a sequence of characters into floating-point numbers. The float() function will help us with this. Its syntax does not differ from the function discussed in the previous chapter. It's worth noting that a float number must contain a period, not a comma. Otherwise, Python simply won't be able to interpret the number passed in the string. 

Here is an example of how to use the function:

example_string = "112.112"
result = float(example_string)
print(result)

This example will convert the character sequence 112.112 into a floating point number. The result is shown in the image below.

Image5

In addition to the above function, we should mention the round() function. It allows you to specify the required number of digits after the point. 

For example, if we need the final number to contain only one digit after the dot when converting the string, we should declare the round() function and pass the corresponding argument:

example_string = "112.112"
result = round(float(example_string),1)
print(result)

After these transformations, the result is as follows:

Image3

String → List

Let's look at converting strings to lists in Python, specifically the split() function. 

Lists are comma-enumerated elements enclosed in square brackets. All elements of a list have their unique identifier (index). The data types of the elements may differ.

Now, let's talk about the split() function itself. It splits a string into a list of substrings using a delimiter. By default, it is equal to a space, but it can be changed if necessary. For this purpose, when calling the function, you should specify a unique delimiter, which will be used to form a list of the sequence of characters.

Let's try to apply this function:

example_string = "Monkey-Lion-Tiger"
example_list = example_string.split("-")
print(example_list)

This will give us a list of 3 items as shown in the image below.

Image1

String → Date

While writing code, a programmer may need to convert a string into a date. For this case, Python also has special modules.

strptime method

This method belongs to the datetime module. It creates a date and time object from a string matching the specified format. 

The syntax is as follows:

datetime.strptime (date_string, date_format)

Consider the example below, where we have a sequence of characters 2023-01-01 12:30:31 that we need to convert to date and time. First of all, initialize the module and then write the rest of the code:

from datetime import datetime

date_string = "2023-01-01 12:30:31"
date_object = datetime.strptime(date_string, "%Y-%d-%m %H:%M:%S")
print(date_object)

The date and time format in the example is %Y-%d-%m %H:%M:%S, but it may be different for you because it depends on the date format in the source string.

As you can see from the picture below, the conversion was successful.

Image2

parser.parse function

Now, let's move on to the dateutil module and its parser.parse function. It works the same way as the previous method, but there is one difference. The parser.parse function automatically determines the format of the specified date. 

The syntax of the function call looks as follows:

parser.parse(example_string)

Now let's consider its use by example, remembering to declare the module at the beginning of the code:

from dateutil import parser

date_string = "2023-01-01 12:30:31"
date_object = parser.parse(date_string)
print(date_object)

In the example, we used the familiar date and time. The result is the same as in the previous method.

Image2

String → Function

A function is a code fragment that performs a specific task and can be used many times. When this code fragment is assigned to a string type variable, you may need to convert it into a function. The built-in eval() function will help with this.

eval() analyzes all the data passed to it as an argument and executes the resulting expression if possible. 

Its syntax is as follows:

eval(expression)

Let's look at the use of eval() with an example:

example_string = "print('Hello, user!')"
eval(example_string)

In this example, we store the call to print() in the example_string variable. eval(), in turn, takes the contents of this variable as an argument and calls the read expression. 

As you can see from the picture below, the function call has been successfully executed.

Image9

Use the above function carefully. You should always control the expression that eval() accepts. If passed in from the outside, for example, by other users, it can harm your system. 

String → Bytes

Bytes are a sequence that, unlike strings, are made up of individual bytes. Their syntax is roughly the same as a regular sequence of characters. The only difference is the prefix b before the beginning of the sequence.

The encode() function will help us convert strings to bytes in Python. It will encode the character sequence and return a string of bytes. All you need to specify when calling it is the encoding. The default encoding is utf-8.

Let's look at the example:

example_string = "Hello, user!"
example_bytes = example_string.encode()
print(example_bytes)

The result is a byte version of the specified string in the example_string variable, as shown in the image below.

Image6

If you want to decode the bytes object back to its original form, use the decode() function.

String → Dictionary

A dictionary is a kind of data structure that stores data in the key-value form.

Let's look at two ways to convert a string to a dictionary in Python. 

json.loads()

The first function we consider is json.loads(). It refers to the json module. It takes an initial sequence of characters in JSON format and converts it into a dictionary.

At the beginning of your code, make sure to import the json module.

Example:

import json

json_string = '{"animal": "Dog", "breed": "Labrador", "age": 9}'
result = json.loads(json_string)
print(result)

As a result, we ended up with a dictionary with 3 pairs, demonstrated in the picture below.

Image7

ast.literal_eval()

The next method is ast.literal_eval(). It belongs to the ast module and performs the same function as the previous method.

Let's go straight to the example, remembering to import the required module at the beginning of the code:

import ast

example_string = "{'animal': 'Dog', 'breed': 'Labrador', 'age': 9 }"
result = ast.literal_eval(example_string)
print(result)

Here we have used the same data as in the previous example. As a result, we got exactly the same dictionary as when we used the json.loads() method.

Image7

The only difference between the json.loads() and the ast.literal_eval() methods is that the character sequence the latter accepts must be in dictionary format rather than JSON format.

Conclusion

In this tutorial, we covered seven types of string conversion. We have also provided examples and alternative conversion methods for each of them. We hope the information you got from this article will help you correctly interact with the string data type when writing code.


Share