zoukankan      html  css  js  c++  java
  • Python之路第五天,基础(5)-序列化和字符串格式化

    序列化

    Python中用于序列化的两个模块

    • json 用于『字符串』和『python基本数据类型』间进行转换
    • pickle 用于『python特有的类型』和『python基本数据类型』间进行转换

    json模块提供了四个功能:dumps、dump、loads、load

    pickle模块提供了四个功能:dumps、dump、loads、load

    例子:
    json:

    #!/usr/bin/env python3
    import json
    user_info = {'name':'tom','age':18}
    user_str = json.dumps(dic)
    print(user_str,type(user_str))
    
    data = json.loads(s)
    print(data,type(data))
    
    with open('user.txt', 'w') as f:
        json.dump(user_info,f)
    
    with open('user.txt', 'r') as f:
        user_info = json.load(f)
    
    print(user_info,type(user_info))
    
    
    结果:
    {"age": 18, "name": "tom"} <class 'str'>
    {'age': 18, 'name': 'tom'} <class 'dict'>
    {'age': 18, 'name': 'tom'} <class 'dict'>
    

    查看文件内容:

    {root@localhost ~} # cat user.txt
    {"age": 18, "name": "tom"}
    

    pickle:

    #!/usr/bin/env python3
    
    import pickle
    
    user_info = {'name':'tom','age':18}
    user_str = pickle.dumps(user_info)
    print(user_str,type(user_str))
    
    data = pickle.loads(user_str)
    print(data,type(data))
    
    with open('user.txt', 'wb') as f:
        pickle.dump(user_info,f)
    
    
    with open('user.txt', 'rb') as f:
        user_info = pickle.load(f)
    
    print(user_info,type(user_info))
    
    结果:
    b'x80x03}qx00(Xx03x00x00x00ageqx01Kx12Xx04x00x00x00nameqx02Xx03x00x00x00tomqx03u.' <class 'bytes'>
    {'age': 18, 'name': 'tom'} <class 'dict'>
    {'age': 18, 'name': 'tom'} <class 'dict'>
    

    查看文件内容:

    [root@localhost ~]# cat user.txt
    (XageqKXnameqXtomqu.
    

    字符串格式化

    Python的字符串格式化有两种方式: 百分号方式、format方式
    百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。[PEP-3101]

    百分号方式

    %[(name)][flags][width].[precision]typecode
    
    • (name) 可选,用于选择指定的Key
    • flags 可选,可选择的值有:
      • + 右对齐,正数前加正好,负数前加负号
      • - 左对齐,正数前无符号,负数前加负号
      • 空格 右对齐,正数前加空格,负数前加负号
      • 0 右对齐,正数前无符号,负数前加负号,用0填充空白处
    • width 可选,占用宽度
    • .precision 可选,小数点后保留的位数
    • typecode 必写
      • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
      • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
      • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
      • o,将整数转换成 八 进制表示,并将其格式化到指定位置
      • x,将整数转换成十六进制表示,并将其格式化到指定位置
      • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
      • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
      • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
      • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
      • F,同上
      • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
      • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
      • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

    常用的格式化例子:

    >>> s = "I'am %s" % 'tom'
    >>> print(s)
    I'am tom
    
    >>> s = "I'am %s,%d years old!" % ('tom',18)
    >>> print(s)
    I'am tom,18 years old!
    
    >>> s = "I'm %(name)s, %(age)d years old!" % {'name':'jerry','age':20}
    >>> print(s)
    I'm jerry, 20 years old!
    
    >>> s =  "percent %.2f" % 99.97643
    >>> print(s)
    percent 99.98
    
    >>> s = "I have %(percent).2f confidence" % {'percent':99.991}
    >>> print(s)
    I have 99.99 confidence
    
    >>> s = "I have %(percent).2f%% confidence" % {'percent':99.991}
    >>> print(s)
    I have 99.99% confidence
    
    

    Format方式

    [[fill]align][sign][#][0][width][,][.precision][type]
    
    1. fill 可选,空白处填充的字符
    2. align 可选,对齐方式(需配合width使用)
      • < ,内容左对齐
      • > ,内容右对齐(默认)
      • = ,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
      • ^ ,内容居中
    3. sign 可选,有无符号数字
      • +,正号加正,负号加负;
      • -,正号不变,负号加负;
      • 空格 ,正号空格,负号加负;
    4. # 可选,对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
    5. , 可选,为数字添加分隔符,如:1,000,000
    6. width 可选,格式化位所占宽度
    7. .precision 可选,小数位保留精度
    8. type 可选,格式化类型
      • 传入” 字符串类型 “的参数
      • s,格式化字符串类型数据
      • 空白,未指定类型,则默认是None,同s
      • 传入“ 整数类型 ”的参数
      • b,将10进制整数自动转换成2进制表示然后格式化
      • c,将10进制整数自动转换为其对应的unicode字符
      • d,十进制整数
      • o,将10进制整数自动转换成8进制表示然后格式化;
      • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
      • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
      • 传入“ 浮点型或小数类型 ”的参数
      • e, 转换为科学计数法(小写e)表示,然后格式化;
      • E, 转换为科学计数法(大写E)表示,然后格式化;
      • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • g, 自动在e和f中切换
      • G, 自动在E和F中切换
      • %,显示百分比(默认显示小数点后6位)

    常用的format方式格式化的例子:

    >>> s = "I am {},{} years old,{},how about you?".format('jack', 18, 'rose')
    >>> print(s)
    I am jack,18 years old,rose,how about you?
    
    >>> s = "i am {}, age {}, {}, how about you?".format(*['jack', 18, 'rose'])
    >>> print(s)
    i am jack, age 18, rose, how about you?
    
    >>> s = "I am {0}, {1} years old, really {0}".format('tom', 18)
    >>> print(s)
    I am tom, 18 years old, really tom
    
    >>> s = "I am {0}, {1} years old, really {0}".format(*['tom',18])
    >>> print(s)
    I am tom, 18 years old, really tom
    
    >>> s =  "I am {name}, {age} years old, really {name}".format(name='tom', age=18)
    >>> print(s)
    I am tom, 18 years old, really tom
    
    >>> s =  "I am {name}, {age} years old, really {name}".format(**{'name':'tom','age':18})
    >>> print(s)
    I am tom, 18 years old, really tom
    
    >>> s = "{0[0]} apple, {0[1]} bananas, {1[0]} oranges".format([1, 2, 3], [11, 22, 33])
    >>> print(s)
    1 apple, 2 bananas, 11 oranges
    
    >>> s = "I am {:s}, {:d} years old,  have {:f} dollars".format('jack', 18, 88888.1)
    >>> print(s)
    I am jack, 18 years old,  have 88888.100000 dollars
    
    >>> s = "I am {:s}, {:d} years old!".format(*['tom', 18])
    >>> print(s)
    I am tom, 18 years old!
    
    >>> s = "I am {name:s}, {age:d} years old!".format(name='tom', age=18)
    >>> print(s)
    I am tom, 18 years old!
    
    >>> s = "I am {name:s}, {age:d} years old!".format(**{'name':'tom', 'age':18})
    >>> print(s)
    I am tom, 18 years old!
    
    >>> s = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
    >>> print(s)
    numbers: 1111,17,15,f,F, 1587.623000%
    
    >>> s = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
    >>> print(s)
    numbers: 1111,17,15,f,F, 1500.000000%
    
    >>> s = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
    >>> print(s)
    numbers: 1111,17,15,f,F, 1500.000000%
    
    
  • 相关阅读:
    Atitit 集团与个人的完整入口列表 attilax的完整入口 1. 集团与个人的完整入口列表 1 2. 流量入口概念 2 3. 流量入口的历史与发展 2 1.集团与个人的完整入口列表
    atitit 每季度日程表 每季度流程 v3 qaf.docx Ver history V2 add diary cyar data 3 cate V3 fix detail 3cate ,
    Atitit react 详细使用总结 绑定列表显示 attilax总结 1. 前言 1 1.1. 资料数量在百度内的数量对比 1 1.2. 版本16 v15.6.1 1 1.3. 引入js 2
    Atitit r2017 r3 doc list on home ntpc.docx
    Atitit r2017 ra doc list on home ntpc.docx
    Atiitt attilax掌握的前后技术放在简历里面.docx
    Atitit q2016 qa doc list on home ntpc.docx
    Atitit r7 doc list on home ntpc.docx 驱动器 D 中的卷是 p2soft 卷的序列号是 9AD0D3C8 D:\ati\r2017 v3 r01\
    Atitit 可移植性之道attilax著
    Atitit q2016 q5 doc list on home ntpc.docx
  • 原文地址:https://www.cnblogs.com/zhangxunan/p/5567032.html
Copyright © 2011-2022 走看看