Summary of python type conversion methods
How to type conversion in python?
Related recommendations: "python video"
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 'int'>,转换内置类 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 类型。
'中国'.encode() # b'\xe4\xb8\xad\xe5\x9b\xbd'bytes('中国', encoding='utf-8') # b'\xe4\xb8\xad\xe5\x9b\xbd'
list
支持转换为 list 的类型,只能是序列,比如:str、tuple、dict、set等。
str -> list
list('123abc') # ['1', '2', '3', 'a', 'b', 'c']
bytes -> list
bytes 转换列表,会取每个字节的 ASCII 十进制值并组合成列表
list(b'hello') # [104, 101, 108, 108, 111]
tuple -> list
tuple 转换为 list 比较简单。
list((1, 2, 3)) # [1, 2, 3]
dict -> list
字典转换列表,会取键名作为列表的值。
list({'name': 'hello', 'age': 18}) # ['name', 'age']
set -> list
集合转换列表,会先去重为标准的集合数值,然后再转换。
list({1, 2, 3, 3, 2, 1}) # [1, 2, 3]
tuple
与列表一样,支持转换为 tuple 的类型,只能是序列。
str -> tuple
tuple('中国人') # ('中', '国', '人')
bytes -> tuple
bytes 转换元组,会取每个字节的 ASCII 十进制值并组合成列表。
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
使用 json 模块
使用 json 模块转换 JSON 字符串为字典时,需要求完全符合 JSON 规范,尤其注意键和值只能由单引号包裹,否则会报错。
import json user_info = '{"name": "john", "gender": "male", "age": 28}' print(json.loads(user_info)) # {'name': 'john', 'gender': 'male', 'age': 28}
使用 eval 函数
因为 eval 函数能执行任何符合语法的表达式字符串,所以存在严重的安全问题,不建议。
user_info = "{'name': 'john', 'gender': 'male', 'age': 28}" print(eval(user_info)) # {'name': 'john', 'gender': 'male', 'age': 28}
使用 ast.literal_eval 方法
使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval。
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
通过 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 = {'a', 'b', 'c'} print(dict(zip(set1, set2))) # {1: 'c', 2: 'a', 3: 'b'}
set
str -> set
先将字符切割成元组,然后再去重转换为集合。
print(set('hello')) # {'l', 'o', 'e', 'h'}
bytes -> set
会取每个字节的 ASCII 十进制值并组合成元组,再去重。
set(b'hello') # {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({'name': 'hello', 'age': 18}) # {'age', 'name'}
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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 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 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.

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.

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.

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.

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.
