全栈成长-python各数据类型之间的转换

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)    #sep为切割规则 默认值为空格   maxsplit为最大切割几次  默认值为-1 返回值为列表
    "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类型之间的转换
  • 什么是bytes类型

    • 二进制数据流bytes
    • 一种特殊的字符串(可以使用字符串的内置方法)
    • 字符串前面加 b 标记 b"字符串"
  • bytes类型可以用字符串的一些方法 但是参数也要是bytes类型

    • str_value="python"   #定义字符串类型
      str_bytes=b"python"  #定义bytes类型
      str_bytes.find(b"p") #传入参数为bytes的才能执行
      
  • 字符串转bytes的函数

方法名 使用
encode(encoding=“utf-8”,errors=“strict”) encoding:转换之后的编码格式(ascii,gbk,默认utf-8)
返回值为bytes errors:出现错误时的方法(默认strict,直接抛出错误;ignore:忽略错误)
  • bytes转为字符串(基本同上)
方法名 使用
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
今日推荐