Full stack growth - conversion between various data types in python

Python data type conversion

Conversion between strings and numbers
primitive type target type function example
integer string str str(123)=>“123”
floating point string str str(3.14)=>“3.14”
string integer int int("123")=>123 int(3.14)=>report error
string floating point float float("3.14")=>3.14 float("314")=>314.0 Other types report an error
Conversion between strings and lists
primitive type target type function example describe
string the list split(sep,maxsplit) “p,y,t,h,o,n”.split(“,”)=>[“p”,“y”,“t”,“h”,“o”,“n”] sep is the cutting rule, the default value is a space, maxsplit is the maximum number of cutting times, the default value is -1, and the return value is a list
the list string sep.join(list) “_”.join([“p”,“y”,“t”,“h”])=>“p_y_t_h” sep is a list tuple collection of non-numeric types for the connection rule list, and a value of numeric type is not acceptable
  • string to 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"] #切割两次后停止
    
  • convert list to string

    #字符串转列表 列表排序后转字符串   可以实现给字符串排序
    "_".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"])=> #有数字  会报错  
    
Conversion between string and bytes types
  • What is the bytes type

    • binary data stream bytes
    • A special kind of String (you can use String's built-in methods)
    • Add b in front of the string to mark b"string"
  • bytes类型可以用字符串的一些方法 但是参数也要是bytes类型

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

method name use
encode(encoding=“utf-8”,errors=“strict”) encoding: encoding format after conversion (ascii, gbk, default utf-8)
The return value is bytes errors: The method when an error occurs (the default is strict, throwing an error directly; ignore: ignore the error)
  • bytes to string (basically the same as above)
method name use
decode(encoding=“utf-8”,errors=“strict”) encoding: encoding format after conversion (ascii, gbk, default utf-8)
The return value is a string errors: The method when an error occurs (the default is strict, throwing an error directly; ignore: ignore the error)
Conversion of lists, sets, and tuples
primitive type target type function example return type
list list gather set set([1,2,3,]) set collection
list list tuple tuple tuple([1,2,3]) tuple
tuple gather set set((1,2,3)) gather
tuple the list list list((1,2,3)) the list
gather the list list list({1,2,3}) the list
gather tuple tuple tuple({1,2,3}) tuple

Guess you like

Origin blog.csdn.net/qq_51075057/article/details/130522643