search
HomeBackend DevelopmentPython TutorialSummary of python type conversion methods

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
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.