zoukankan      html  css  js  c++  java
  • 精细化Python-字符串格式化

     1、概述

        在Python中,字符串属于不可变有序序列,使用单引号、双引号、三单引号或三双引号作为定界符,并且不同的定界符之间可以互相嵌套

        Python支持字节串类型bytes,str类型字符串可以通过encode()方法使用指定的字符串编码格式编码成为bytes对象,而bytes对象则可以通过decode()方法使用指定编码格式解码成为str字符串。

        Python 3.x完全支持中文字符,默认使用UTF8编码格式,无论是一个数字、英文字母,还是一个汉字(无论汉字的编码是二字节三字节或四字节),在统计字符串长度时都按一个字符对待和处理。

             转义字符

    转义字符

    含义

    转义字符

    含义

    

    退格,把光标移动到前一列位置

    \

    一个斜线

    f

    换页符

    单引号’

    换行符

    双引号”

    回车

    ooo

    3位八进制数对应的字符

    水平制表符

    xhh

    2位十六进制数对应的字符

    v

    垂直制表符

    uhhhh

    4位十六进制数表示的Unicode字符

             在字符串前面加上字母 r 或 R 表示原始字符串,其中的所有字符都表示原始的含义而不会进行任何转义。

        2、格式化

                   格式化字符串时,Python使用一个字符串作为模板。模板中有格式符,这些格式符为真实值预留位置,并说明真实数值应该呈现的格式。Python用一个tuple将多个值传递给模板,每个值对应一个格式符。

         ①使用%运算符进行格式化

        '%[(name)][flags][width].[precision]typecode'%(表达式)

        (name)为命名

        flags可以有+,-,' '或0。+表示正数添加‘+‘号。-表示负对齐(字符串正对齐为左,数值正对齐为右)。' '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。

        width表示显示宽度

        precision表示小数点后精度

                     常用格式字符typecode

        ②使用format方法进行格式化

        1)format基本用法

    • -  不带编号----    {}
    • -  带数字编号,可调换顺序 {0},{1},{2}...
    • -  带关键字,{name},{age}....

      >>> print('My name is {},age:{}'.format('CDS',19))

      My name is CDS,age:19

      >>> print('My name is {1},age:{0}'.format(20,'CDS',19))

      My name is CDS,age:20

      >>> print('My name is {name},age:{age}'.format(classname='ji1',name='CDS',age=19,chinese=122))

      My name is CDS,age:19

        2)format的进阶用法

    • a·        <(默认)左对齐,> 右对齐,^中间对齐
    • b·        取位数“{:4s}”,“{:.2f}“    #可与a 中格式联合
    • %   _    ,  财务格式:百分比、分隔符等  #Python 3.6.0及更高版本支持且不与其他格式混合,当为int时,可连接数字进制格式 如 d,o,x等,当为float时,可连接 .nf        

      >>> print('{0:^10.3f}'.format(1/3))         #保留3位小数,且居中对齐,0可不写

      0.333

      >>> ‘{:%}’.format(3.5)                  #格式化为百分数

      '350.000000%'

      >>> ‘{:.2%}’.format(1/3)                 #转换为百分比,且保留两位小数

      '33.33%‘

      >>> '{0:_},{0:_x}'.format(1000000)       #Python 3.6.0及更高版本支持

      '1_000_000,f_4240'

      >>> ‘{0:,}16进制是{0:_x}'.format(10000000)      #Python 3.6.0及更高版本支持

      '10,000,000 16进制是98_9680'

            format格式也可赋值给变量,如: 

      weather = [("Monday","rainy"),("Tuesday","sunny"),  ("Wednesday", "sunny"),

        ("Thursday","rainy"), ("Friday","cloudy")]

      formatter = "Weather of '{0[0]}' is '{0[1]}'".format

      for item in map(formatter,weather):

            print(item)

           这个for循环也可写成如下

      for item in weather:

            print(formatter(item))

      运行结果:

      Weather of 'Monday' is 'rainy'

      Weather of 'Tuesday' is 'sunny'

      Weather of 'Wednesday' is 'sunny'

      Weather of 'Thursday' is 'rainy'

      Weather of 'Friday' is 'cloudy'

       ③格式化的字符串常量 f-string

    • 从Python 3.6.x开始支持一种新的字符串格式化方式,在字符串前加字母f,含义与字符串对象format()方法类似。

      >>> name = 'Cheng'

      >>> age = 29

      >>>height=1.75

      >>> f'My name is {name}, and I am {age} years old. My height is {height} m'

      'My name is Cheng, and I am 29 years old. My height is 1.75 m'

      >>> print(f'My name is {name:^8s}, and I am{age:^4d} years old. My height is {height:^6.2f} m.')

      My name is  Cheng  , and I am 29  years old. My height is  1.75  m.

      >>> width = 10

      >>> precision = 4

      >>> value = 11/3

      >>> f'result:{value:{width}.{precision}}'

      'result:     3.667'

      f-string大括号内也可填入lambda表达式,但lambda表达式的 : 会被f-string误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将lambda表达式置于圆括号 () 内:

      >>>print(f'My name is {name:^8s}, and I am{age:^4d} years old. My height is {height:^6.2f} m.My weight is {(lambda x:x*2)(age+height):^6.2f} kg .')

      My name is  Cheng  , and I am 29  years old. My height is  1.75  m.My weight is 61.50  kg.

  • 相关阅读:
    php -- php数组相关函数
    php -- 数组排序
    php -- in_array函数
    php -- 魔术方法 之 删除属性:__unset()
    无符号整型与有符号整型相运算规则
    N个节点的二叉树有多少种形态
    getopt_long
    typedef
    约瑟夫环问题算法(M)
    C语言基础
  • 原文地址:https://www.cnblogs.com/cjtds/p/12978280.html
Copyright © 2011-2022 走看看