全栈成长-python各数据类型之间的转换
移动开发
2023-07-30 04:59:10
阅读次数: 0
python数据类型的转换
字符串与数字之间的转换
原始类型 |
目标类型 |
函数 |
举例 |
整型 |
字符串 |
str |
str(123)=>“123” |
浮点型 |
字符串 |
str |
str(3.14)=>“3.14” |
字符串 |
整型 |
int |
int(“123”)=>123 int(3.14)=>报错 |
字符串 |
浮点型 |
float |
float(“3.14”)=>3.14 float(“314”)=>314.0 其他类型报错 |
字符串与列表之间的转换
原始类型 |
目标类型 |
函数 |
举例 |
描述 |
字符串 |
列表 |
split(sep,maxsplit) |
“p,y,t,h,o,n”.split(“,”)=>[“p”,“y”,“t”,“h”,“o”,“n”] |
sep为切割规则 默认值为空格 maxsplit为最大切割几次 默认值为-1 返回值为列表 |
列表 |
字符串 |
sep.join(list) |
“_”.join([“p”,“y”,“t”,“h”])=>“p_y_t_h” |
sep 为连接规则 list非数字类型的列表元组集合 一个数字类型的值都不行 |
-
字符串转列表
split(sep,maxsplit)
"p,y,t,h,o,n".split(",")=>["p","y","t","h","o","n"]
"p,y,t,h,o,n".split(",",2)=>["p","y","thon"]
-
列表转换为字符串
"_".join([“p”,"y","t","h"])=>"p_y_t_h"
".".join([“p”,"y","t","h"])=>"p.y.t.h"
"".join([“p”,"y","t","h"])=>"pyth"
".".join([1,"y","t","h"])=>
字符串与bytes类型之间的转换
方法名 |
使用 |
encode(encoding=“utf-8”,errors=“strict”) |
encoding:转换之后的编码格式(ascii,gbk,默认utf-8) |
返回值为bytes |
errors:出现错误时的方法(默认strict,直接抛出错误;ignore:忽略错误) |
方法名 |
使用 |
decode(encoding=“utf-8”,errors=“strict”) |
encoding:转换之后的编码格式(ascii,gbk,默认utf-8) |
返回值为字符串 |
errors:出现错误时的方法(默认strict,直接抛出错误;ignore:忽略错误) |
列表、集合、元组的转换
原始类型 |
目标类型 |
函数 |
例子 |
返回值类型 |
列表list |
集合 |
set |
set([1,2,3,]) |
set集合 |
列表list |
元组 |
tuple |
tuple([1,2,3]) |
元组 |
元组 |
集合 |
set |
set((1,2,3)) |
集合 |
元组 |
列表 |
list |
list((1,2,3)) |
列表 |
集合 |
列表 |
list |
list({1,2,3}) |
列表 |
集合 |
元组 |
tuple |
tuple({1,2,3}) |
元组 |
转载自blog.csdn.net/qq_51075057/article/details/130522643