Home Backend Development Python Tutorial Summary of python type conversion methods

Summary of python type conversion methods

Jun 15, 2019 pm 04:46 PM
python type conversion

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login

float -> complex

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

complex(-12.09)     # (-12.09+0j)
Copy after login

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')      # 报错,加号两侧不可有空格
Copy after login

str

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

int -> str

int Converting str will directly convert it completely.

str(12)     # 12
Copy after login

float -> str

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

str(-12.90)     # -12.9
Copy after login

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)
Copy after login

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'
Copy after login

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')  # 中国
Copy after login

list -> str

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

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

tuple -> str

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

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

dict -> str

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

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

set -> str

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

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

其他类型

转换内置对象:

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

转换类实例:

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

转换函数:

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

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;
Copy after login

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;]
Copy after login

bytes -> list

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

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

tuple -> list

tuple 转换为 list 比较简单。

list((1, 2, 3))     
# [1, 2, 3]
Copy after login

dict -> list

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

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

set -> list

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

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

tuple

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

str -> tuple

tuple(&#39;中国人&#39;)    
# (&#39;中&#39;, &#39;国&#39;, &#39;人&#39;)
Copy after login

bytes -> tuple

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

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

list -> tuple

tuple([1, 2, 3])    
# (1, 2, 3)
Copy after login

dict -> tuple

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

set -> tuple

tuple({1, 2, 3, 3, 2, 1})
# (1, 2, 3)
Copy after login

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}
Copy after login

使用 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}
Copy after login

使用 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}
Copy after login

list -> dict

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

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

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

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

tuple -> dict

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

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

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

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

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;}
Copy after login

set

str -> set

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

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

bytes -> set

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

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

list -> set

先对列表去重,再转换。

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

tuple -> set

先对列表去重,再转换。

 set((1, 2, 3, 2, 1))    # {1, 2, 3}
Copy after login

dict -> set

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

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

    

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles