Home  >  Article  >  Backend Development  >  Summary of python type conversion methods

Summary of python type conversion methods

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-15 16:46:537900browse

How to type conversion in python?

Related recommendations: "python video"

Summary of python type conversion methods

int

Supports conversion to int type, only float, str, bytes, other types None are supported.

float -> int

will remove the decimal point and the following values, leaving only the integer part.

int(-12.94)     # -12

str -> int

If there are characters other than numbers (0-9) and signs (/-) in the string, an error will be reported .

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

bytes -> int

If bytes contains characters other than numbers (0-9) and signs (/-), an error will be reported.

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

float

Supports conversion to float type, only int, str, bytes, other types are not supported.

int -> float

When converting int to float, one decimal place will be added automatically.

float(-1209)     # -1209.0

str -> float

If the string contains characters other than sign (/-), numbers (0-9) and decimal point (.) , conversion is not supported.

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

bytes -> float

If bytes contains characters other than signs (/-), numbers (0-9) and decimal points (.) , conversion is not supported.

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

complex

Only supports int, float, str conversion to complex type.

int -> complex

int When converting complex, the imaginary part will be automatically added and represented by 0j.

complex(12)         # (12+0j)

float -> complex

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

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

str -> complex

str When converting complex, if it can be converted to int or float, it will be converted and then converted to complex. If the string completely conforms to the complex expression rules, it can also be converted to a complex type value.

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')          # 报错,不支持 bytes 转换为 complex
complex('12 + 9j')      # 报错,加号两侧不可有空格

str

str() function can convert any object into a string.

int -> str

int Converting str will directly convert it completely.

str(12)     # 12

float -> str

float Converting str will remove the decimal part with the last 0.

str(-12.90)     # -12.9

complex -> str

complex conversion to str will first convert the value into a standard complex expression, and then convert it into a string.

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

bytes -> str

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

Convert to an executable expression string:

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

The str() function specifies the encoding parameter, or you can use the bytes.decode() method to convert 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

会先将值格式化为标准的 list 表达式,然后再转换为字符串。

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

tuple -> str

会先将值格式化为标准的 tuple 表达式,然后再转换为字符串。

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

dict -> str

会先将值格式化为标准的 dict 表达式,然后再转换为字符串。

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

set -> str

会先将值格式化为标准的 set 表达式,然后再转换为字符串。

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

其他类型

转换内置对象:

str(int)    # <class &#39;int&#39;>,转换内置类
str(hex)    # <built-in function hex>,转换内置函数

 转换类实例:

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

转换函数:

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

bytes

仅支持 str 转换为 bytes 类型。

&#39;中国&#39;.encode()                   
# b&#39;\xe4\xb8\xad\xe5\x9b\xbd&#39;bytes(&#39;中国&#39;, encoding=&#39;utf-8&#39;)   
# b&#39;\xe4\xb8\xad\xe5\x9b\xbd&#39;

list

支持转换为 list 的类型,只能是序列,比如:str、tuple、dict、set等。

str -> list

list(&#39;123abc&#39;)      
# [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

bytes -> list

bytes 转换列表,会取每个字节的 ASCII 十进制值并组合成列表

list(b&#39;hello&#39;)      
# [104, 101, 108, 108, 111]

tuple -> list

tuple 转换为 list 比较简单。

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

dict -> list

字典转换列表,会取键名作为列表的值。

list({&#39;name&#39;: &#39;hello&#39;, &#39;age&#39;: 18})  
# [&#39;name&#39;, &#39;age&#39;]

set -> list

集合转换列表,会先去重为标准的集合数值,然后再转换。

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

tuple

与列表一样,支持转换为 tuple 的类型,只能是序列。

str -> tuple

tuple(&#39;中国人&#39;)    
# (&#39;中&#39;, &#39;国&#39;, &#39;人&#39;)

bytes -> tuple

bytes 转换元组,会取每个字节的 ASCII 十进制值并组合成列表。

tuple(b&#39;hello&#39;)     
# (104, 101, 108, 108, 111)

list -> tuple

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

dict -> tuple

tuple({&#39;name&#39;: &#39;hello&#39;, &#39;age&#39;: 18})     
# (&#39;name&#39;, &#39;age&#39;)

set -> tuple

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

dict

str -> dict

使用 json 模块

使用 json 模块转换 JSON 字符串为字典时,需要求完全符合 JSON 规范,尤其注意键和值只能由单引号包裹,否则会报错。

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

使用 eval 函数

因为 eval 函数能执行任何符合语法的表达式字符串,所以存在严重的安全问题,不建议。

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

使用 ast.literal_eval 方法

使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval。

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

list -> dict

通过 zip 将 2 个列表映射为字典:

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

将嵌套的列表转换为字典:

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

tuple -> dict

通过 zip 将 2 个元组映射为字典:

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

将嵌套的元组转换为字典:

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

set -> dict

通过 zip 将 2 个集合映射为字典:   

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

set

str -> set

先将字符切割成元组,然后再去重转换为集合。

print(set(&#39;hello&#39;))     # {&#39;l&#39;, &#39;o&#39;, &#39;e&#39;, &#39;h&#39;}

bytes -> set

会取每个字节的 ASCII 十进制值并组合成元组,再去重。   

set(b&#39;hello&#39;)           # {104, 108, 101, 111}

list -> set

先对列表去重,再转换。

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

tuple -> set

先对列表去重,再转换。

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

dict -> set

会取字典的键名组合成集合。

set({&#39;name&#39;: &#39;hello&#39;, &#39;age&#39;: 18})
# {&#39;age&#39;, &#39;name&#39;}

    

The above is the detailed content of Summary of python type conversion methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn