Login With Github

Most Complete Guide For Python 3 Type Conversion

int

Only the types of floatstr, and bytes are supported to be converted to int type, other types are not supported.

float -> int

The decimal point and the followed values ​​will be removed, leaving only the integer part.

int(-12.94)     # -12

str -> int

If there are characters other than numbers (0-9), and plus/minus (+/-) in the string, an error will be thrown.

int('1209')     # 1209
int('-12')      # -12
int('+1008')    # 1008

bytes -> int

If there are characters other than numbers (0-9), and plus/minus (+/-) in bytes, an error will be thrown.

int(b'1209')     # 1209
int(b'-12')      # -12
int(b'+1008')    # 1008

float

Only the types of intstr, and bytes are supported to be converted to float type, other types are not supported.

int -> float

The value will be added one decimal automatically.

float(-1209)     # -1209.0

str -> float

If there are characters other than plus/minus (+/-), number (0-9), and decimal point (.) in the string, the conversion won't be supported.

float('-1209')          # -1209.0
float('-0120.29023')    # -120.29023

bytes -> float

If there are characters other than plus/minus (+/-), number (0-9), and decimal point (.) in the byte, the conversion won't be supported.

float(b'-1209')         # -1209.0
float(b'-0120.29023')   # -120.29023

complex

Only the types of intfloat, and str are supported to be converted to complex type.

int -> complex

When converting, the imaginary part will be added automatically and represented with 0j.

complex(12)         # (12+0j)

float -> complex

When converting, the imaginary part will be added automatically and represented with 0j.

complex(-12.09)     # (-12.09+0j)

str -> complex

The value will be converted to the type of int or float first if it can, and then to the type of complex. A string can also be converted to a value of the complex type, if it conforms to the rules of complex expression completely.

complex('-12.09')       # (-12.09+0j)
complex('-12.0')        # (-12+0j)
complex('-12')          # (-12+0j)
complex('-12+9j')       # (-12+9j)
complex('(-12+9j)')     # (-12+9j)
complex('-12.0-2.0j')   # (-12-2j)
complex('-12.0-2.09j')  # (-12-2.09j)
complex(b'12')          # throw an exception
complex('12 + 9j')      # throw an exception

str

The str()  function can be used to convert any object as a string.

int -> str

It will be converted directly.

str(12)     # 12

float -> str

It will remove the fractional part with the last digit of 0.

str(-12.90)     # -12.9

complex -> str

The value will be converted to a standard complex expression first and then to a string.

str(complex(12 + 9j))   # (12+9j)
str(complex(12, 9))     # (12+9j)

bytes -> str

The conversion of bytes to str is a little special. In Python 3.x, strings and bytes are no longer confused, but completely different data types.

Convert the value of the bytes type to an executable expression string:

str(b'hello world')        # b'hello world'

The str()  function specifies the encoding parameter, or uses the bytes.decode() method to convert the actual data:

b'hello world'.decode()                             # hello world
str(b'hello world', encoding='utf-8')               # hello world
str(b'\xe4\xb8\xad\xe5\x9b\xbd', encoding='utf-8')

list -> str

The value will be formatted as a standard list expression first and then converted as a string.

str([])                      # []
str([1, 2, 3])              # [1, 2, 3]
''.join(['a', 'b', 'c'])    # abc

tuple -> str

The value will be first formatted as a standard tuple expression and then converted as a string.

str(())                     # ()
str((1, 2, 3))              # (1, 2, 3)
''.join(('a', 'b', 'c'))    # abc

dict -> str

The value will be formatted as a standard dict expression first and then converted as a string.

str({'name': 'hello', 'age': 18})       # {'name': 'hello', 'age': 18}
str({})                                 # {}
''.join({'name': 'hello', 'age': 18})   # nameage

set -> str

The value will be formatted as a standard set expression first and then converted as a string.

str(set({}))                # set()
str({1, 2, 3})              # {1, 2, 3}
''.join({'a', 'b', 'c'})    # abc

Other types

Convert built-in objects:

str(int)                # <class 'int'>,convert a built-in class
str(hex)                # <built-in function hex>,convert a built-in function

An instance of converting as a class:

class Hello:
    pass
obj = Hello()
print(str(obj))
# <__main__.Hello object at 0x1071c6630>

An instance of converting as a function:

def hello():
    pass
print(str(hello))
# <function hello at 0x104d5a048>

bytes

Only the str  type is supported to be converted to the bytes type.

'My'.encode()
bytes('My', encoding='utf-8')

list

Only the sequences, such as: str, tuple, dict, set, and so on, are supported to be converted to the list type.

str -> list

list('123abc')      # ['1', '2', '3', 'a', 'b', 'c']

bytes -> list

It will obtain the ASCII decimal value of each byte and combine them into a list.

list(b'hello')      # [104, 101, 108, 108, 111]

tuple -> list

The Conversion is quite simple.

list((1, 2, 3))     # [1, 2, 3]

dict -> list

It will take the key name as the value of the list when converting.

list({'name': 'hello', 'age': 18})  # ['name', 'age']

set -> list

It will remove the duplicates as a standard collection value first and then convert it to a list.

list({1, 2, 3, 3, 2, 1})    # [1, 2, 3]

tuple

Like the list, Only the sequences are supported to be converted to the tuple type.

str -> tuple

tuple('JAM')    # ('J', 'A', 'M')

bytes -> tuple

It will get the ASCII decimal value of each byte and combine them into a list.

tuple(b'hello')     # (104, 101, 108, 108, 111)

list -> tuple

tuple([1, 2, 3])    # (1, 2, 3)

dict -> tuple

tuple({'name': 'hello', 'age': 18})     # ('name', 'age')

set -> tuple

tuple({1, 2, 3, 3, 2, 1})       # (1, 2, 3)

dict

str -> dict

Use the json module.

When using the json module to convert JSON strings into dictionaries, the strings should be fully comply with the JSON specification. In particular, note that keys and values ​​can only be wrapped by single quotes, otherwise an error will be thrown.

import json
    
user_info = '{"name": "john", "gender": "male", "age": 28}'
print(json.loads(user_info))
    
# {'name': 'john', 'gender': 'male', 'age': 28}

Use the eval function.

Because the eval function can execute any grammar-compliant expression string, there will be serious security issues. It's not recommended.

user_info = "{'name': 'john', 'gender': 'male', 'age': 28}"
print(eval(user_info))
    
# {'name': 'john', 'gender': 'male', 'age': 28}

Use the ast.literal_eval method.

When using ast.literal_eval for conversion, there won't come the problem caused by using json, nor security issue caused by using eval, so it's recommended to do so.

import ast
    
user_info = "{'name': 'john', 'gender': 'male', 'age': 28}"
user_dict = ast.literal_eval(user_info)
print(user_dict)
    
# {'name': 'john', 'gender': 'male', 'age': 28}

list -> dict

Map two lists to a dictionary by zip:

list1 = [1, 2, 3, 4]
list2 = [1, 2, 3]
print(dict(zip(list1, list2)))
# {1: 1, 2: 2, 3: 3}

Convert the nested list to a dictionary:

li = [
    [1, 111],
    [2, 222],
    [3, 333],
]
print(dict(li))
# {1: 111, 2: 222, 3: 333}

tuple -> dict

Map two tuples to a dictionary by zip:

tp1 = (1, 2, 3)
tp2 = (1, 2, 3, 4)
print(dict(zip(tp1, tp2)))
# {1: 1, 2: 2, 3: 3}

Convert the nested tuples to a dictionary:

tp = (
    (1, 111),
    (2, 222),
    (3, 333),
)
print(dict(tp))
# {1: 111, 2: 222, 3: 333}

set -> dict

Map two sets to a dictionary by zip:

set1 = {1, 2, 3}
set2 = {'a', 'b', 'c'}
print(dict(zip(set1, set2)))
# {1: 'c', 2: 'a', 3: 'b'}

set

str -> set

The characters will be cut into tuples first and then re-converted into a collection.

print(set('hello'))     # {'l', 'o', 'e', 'h'}

bytes -> set

It will get the ASCII decimal value of each byte and combine then into tuples, and then remove the duplicates.

set(b'hello')           # {104, 108, 101, 111}

list -> set

It will remove the duplicates in the list first, then convert the result.

set([1, 2, 3, 2, 1])    # {1, 2, 3}

tuple -> set

It will remove the duplicates in the list first, then convert the result.

set((1, 2, 3, 2, 1))    # {1, 2, 3}

dict -> set

It will combine the key names of the dictionary into a collection.

set({'name': 'hello', 'age': 18})
# {'age', 'name'}

0 Comment

temp