Python
Basic Data Types
string
convert

Python string to number, integer, real , binary, hex, datetime, bytes, lists

In this article, you'll learn how to convert Python strings to other data types.

Python strings play an important role in the process of interacting with clients. The data you receive from the input() function, XML, and JSON data from web APIs are all initially formatted as strings. The backend server must interpret or parse the string, convert it to the desired data type, and then perform the necessary actions.

>>> name = input("What is your name?: ")
What is your name? John
 
>>> type(name)
<class 'str'>

1. Convert to Numbers

Let's start with how to convert a Python string to a number in the desired format.

All numeric conversions have the potential to fail. When it does, an exception is thrown, so you should always include exception handling. The sample code below all includes exception handling.

1.1. Integers

To convert a Python string to an integer, use the int() constructor.

💡

Constructors are special functions that are used to create objects of certain Python classes. We'll talk about them in the class article.

Here's an example of a successful integer conversion.

str_one_hundred = "100"
str_minus_five = "-5"
 
try:
    one_hundred = int(str_one_hundred)
    minus_five = int(str_minus_five)
except ValueError:
    print(f"Couldn't cast {repr(str_one_hundred)} to a number")
    print(f"Couldn't cast {repr(str_minus_five)} to a number")
else:
    print(f"one_hundred: {one_hundred}")
    print(f"minus_five: {minus_five}")
 
# Output:
# one_hundred: 100
# minus_five: -5

Examples of failed integer conversions include

str_alphabet = "abc"
 
try:
    alphabet = int(str_alphabet)
except ValueError:
    print(f"Couldn't cast {repr(str_alphabet)} to a number")
else:
    print(f"alphabet: {alphabet}")
 
# Output:
# Couldn't cast 'abc' to a number

1.2. Real numbers

To convert a Python string to a real number, use the float() constructor.

Here is an example of a successful conversion to a real number.

str_three_point_two_four = "3.24"
str_zero_point_one_two = "-0.12"
 
try:
    three_point_two_four = float(str_three_point_two_four)
    zero_point_one_two = float(str_zero_point_one_two)
except ValueError:
    print(f"Couldn't cast {repr(str_three_point_two_four)} to a float")
    print(f"Couldn't cast {repr(str_zero_point_one_two)} to a float")
else:
    print(f"three_point_two_four: {three_point_two_four}")
    print(f"zero_point_one_two: {zero_point_one_two}")
 
# Output:
# three_point_two_four: 3.24
# zero_point_one_two: -0.12

Examples of failed integer conversions include

str_alphabet = "abc"
 
try:
    alphabet = float(str_alphabet)
except ValueError:
    print(f"Couldn't cast {repr(str_alphabet)} to a float")
else:
    print(f"alphabet: {alphabet}")
 
# Output:
# Couldn't cast 'abc' to a float

1.3. Binary

Python does not support its own binary data type. Therefore, binary strings must be converted to integer types in order to manage them.

To convert to integer, use the int() constructor with the optional base parameter.

binary_string = "101010"
binary_integer = int(binary_string, base=2)
print(binary_integer)
 
# Outputs: 42

If you want to output the integer of the result in binary format, you can use the approach discussed in the F-string post. You can also decide whether to add the prefix 0b as a format specifier.

print(f'{binary_integer:#b}', f'{binary_integer:b}')
('0b101010', '101010')

1.4. Hexadecimal

Python does not support its own hexadecimal data type. Therefore, hexadecimal strings must be converted to integer types in order to manage them.

To convert to integer, use the int() constructor with the optional base parameter.

hexa_string = "14F0"
hexa_integer = int(hexa_string, base=16)
print(hexa_integer)
 
# Outputs: 5360

If you want to output the integer of the result in hexadecimal format, you can use the approach discussed in the F-string post. You can also decide whether to add the prefix 0x as a format specifier.

print(f'{hexa_integer:#x}', f'{hexa_integer:x}')
('0x14f0', '14f0')

2. Container types

Python's built-in container types - lists, tuples, sets, and dictionaries - can also be converted from strings. However, if you try to convert them with a constructor, as you would a number, you will get a different result than expected, as shown below.

friends = "[Mark, Elon]"
friends_tuple = "(Mark, Elon)"
 
print(list(friends))
print(tuple(friends_tuple))
 
# Output:
# ['[', 'M', 'a', 'r', 'k', ',', ' ', 'E', 'l', 'o', 'n', ']']
# ('(', 'M', 'a', 'r', 'k', ',', ' ', 'E', 'l', 'o', 'n', ')')

Therefore, we need another way to parse these container types. The literal_eval() function provided by the ast module in the standard Python library provides a convenient way to parse and convert them. This function is a replacement for the eval() function, which can be hacked.

2.1. Lists

Code to convert a string to a list format can be written as follows

import ast
 
list_string = "['item1', 'item2', 'item3']"
 
my_list = ast.literal_eval(list_string)
 
print(my_list)
print(type(my_list))
 
# Output:
# ['item1', 'item2', 'item3']
# <class 'list'>

2.2. Tuples

Code to convert a string to a tuple format can be written like this

import ast
 
tuple_string = "('item1', 'item2', 'item3')"
 
my_tuple = ast.literal_eval(tuple_string)
 
print(my_tuple)
print(type(my_tuple))
 
# Output:
# ('item1', 'item2', 'item3')
# <class 'tuple'>

2.3. Sets

Code to convert a string with a set format can be written as follows

import ast
 
set_string = "{'item1', 'item2', 'item3'}"
 
my_set = ast.literal_eval(set_string)
 
print(my_set)
print(type(my_set))
 
# Output:
# {'item3', 'item2', 'item1'}
# <class 'set'>

2.4. Dictionaries

Code to convert a string with a dictionary format can be written as follows.

import ast
 
dict_string = "{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}"
 
my_dict = ast.literal_eval(dict_string)
 
print(my_dict)
print(type(my_dict))
 
# Output:
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# <class 'dict'>

3. Byte strings

To convert a byte format string to the bytes datatype, use the str.encode() method.

byte_like_string = "b'Hello'"
actual_bytes = byte_like_string[2:-1].encode('utf-8')
print(actual_bytes)  # Outputs: b'Hello'
print(type(actual_bytes))  # Outputs: <class 'bytes'>

It removes the prefix to represent bytes in Python and only converts the contents to the encode() method. You can check the byte type with the type(){;py} function.

4. Date Time

To extract and read date and time information from a Python string, use the strptime() method of the datetime module.

See datetime - 3. Formatting and parsing dates and times for an explanation and sample code. for more information.

5. Conclusion

So far, we've seen how to convert Python strings to several different types, including numbers, container types, byte types, and date and time. String types are a way for programs to communicate with users, so it's important to understand and use them well.

copyright for Python string to number, integer, real , binary, hex, datetime, bytes, lists

© 2023 All rights reserved.