# summary

Data type conversion refers to the conversion of one data from the original type to another type by some means. For example, we convert the string "123" to the number 123, which is a data type conversion.

Python supports the conversion between various standard data types, but not all data can be converted. All conversions should conform to "common sense" and be logically valid. For example, you shouldn't try to convert a complex type to int, because Python doesn't know how to convert either.

# Conversion between various types and examples

## Convert to int

```1 print(int(1.2))  # float -> int
2 print(int('123'))  # string -> int
3 print(int(b'456'))  # bytes -> int
4 print('0x%x' % (int.from_bytes(b'456', byteorder='little', signed=True)))
5 print(int(True))  # bool -> int```

## Convert to float

```1 print(float('1.2'))  # string->float
2 print(float(b'3.4'))  # bytes -> float
3 print(float(123))  # int->float
4 print(float(False))  # bool->float```

## Convert to bool

All types can be converted to bool

``` 1 print(bool(1))  # int->bool
2 print(bool(0.0))  # float->bool
3 print(bool(0 + 0j))  # complex->bool
4 print(bool(''))  # string->bool, Empty string is False,Everything else True
5 print(bool(b'hello'))  # bytes->bool, Empty as False,Everything else True
6 print(bool.from_bytes(b'\x00', byteorder='little'))  # bytes->bool
7 print(bool([]))  # list->bool, Empty as False,Everything else True
8 print(bool(()))  # tuple->bool, Empty as False,Everything else True
9 print(bool({}))  # dict->bool, Empty as False,Everything else True
10 print(bool(set()))  # set->bool, Empty as False,Everything else True```

## Convert to complex

```1 print(complex(100))  # int->complex
2 print(complex(1.2))  # float->complex
3 print(complex(True))  # bool->complex
4 print(complex('1.2+2.3j'))  # string->complex```

## Convert to string

All basic types can be converted to string

```1 print(b'hello'.decode('utf-8'))  # bytes->string
2 print(str(1))  # int->string
3 print(str(1.2))  # float->string
4 print(str(True))  # bool->string
5 print(str(1.2 + 2.3j))  # complex->string Everything else True
6 print(str(['hello', 100]))  # list->string
7 print(str(('hello', 100)))  # tuple->string
8 print(str({'name': 'xiaowang', 'age': 20}))  # dict->string
9 print(str({'name', 'age'}))  # set->string```

## Convert to bytes

Because all types can be converted to string and string can be converted to bytes, all types can be converted indirectly to bytes.
Let's just discuss the type of direct conversion to bytes

```1 print('bytes'.center(30, '*'))
2 print(b'\x64')  # int turn bytes
3 print(int.to_bytes(100, byteorder='big', signed=True, length=2))  # int turn bytes
4 print(bool.to_bytes(True, byteorder='big', signed=True, length=2))  # bool turn bytes
5 print('hello'.encode(encoding='utf-8'))  # string turn bytes
6 print(bytes([1, 200, 80, 50]))  # list turn bytes
7 print(bytes((1, 200, 80, 50)))  # tuple turn bytes
8 print(bytes({1, 200, 80, 50}))  # set turn bytes```

## Convert to list

```1 print(list("hello"))  # string->list
2 print(list(b'hello'))  # bytes->list
3 print(list((100, 200, 300)))  # tuple->list
4 print(list({'name', 'age'}))  # set->list
5 print(list({'name': 'xiaowang', 'age': 20}))  # dict->list， Take only key value7 ```

## Convert to tuple

```1 print(tuple("hello"))  # string->tuple
2 print(tuple(b"hello"))  # bytes->tuple
3 print(tuple([100, 200, 300]))  # list->tuple
4 print(tuple({'name', 'age'}))  # set->tuple
5 print(tuple({'name': 'xiaowang', 'age': 20}))  # dict->tuple， Take only key value```

## Convert to set

```1 print(set("hello"))  # string->set
2 print(set(b"hello"))  # bytes->set
3 print(set([100, 200, 300]))  # list->set
4 # print(set([100, 200, [300, 400]]))  # List - > set. The list contains variable data types and reports exceptions
5 print(set(('name', 'age')))  # tuple->set
6 # print(set(('name', 'age', [])))  # Tuple - > set, including variable data type, reporting exception
7 print(set({'name': 'xiaowang', 'age': 20}))  # dict->set， Take only key value```

## Convert to dict

The method of converting to dict is a little more complicated

### Method 1: use json conversion. The string format needs to be strictly in accordance with the json format

```1 user_str = '{"name": "xiaowang", "city": "Chengdu", "age": 28}'
2 import json

### Mode 2: use eval function conversion, eval has security risks, not recommended

`print(eval(user_str))  `

### Mode 3 use ast.literal_eval

```import ast
print(ast.literal_eval(user_str))  ```

### Method 1: zip is required

```1 user_keys = ['name', 'city', 'age']
2 user_values = ['xiaowang', 'Chengdu', 28]
3 print(dict(zip(user_keys, user_values))) ```

### Mode 2: 2D list

```1 user_info = [
2     ["name", "xiaowang"],
3     ["city", "Chengdu"],
4     ["age", 28]
5     ]
6 print(dict(user_info))  ```

### More of my articles and columns:

Tags: Python JSON encoding

Posted on Wed, 13 May 2020 23:57:26 -0700 by richardwarren