美文网首页
七、格式化输出

七、格式化输出

作者: 胖虎喜欢小红 | 来源:发表于2020-01-07 20:29 被阅读0次

一、

字符串的格式化输出目前有两种方式

  • % 方式(陈旧)
  • str.format() 方式(新式,官方推荐)
  • f-string 方式 (Python3.6 及以上推荐使用)

1、 %方式

tpl = "i am %s" % "zhu"
print(tpl)

tpl = "i am %s age %d" % ("zhu", 18)
print(tpl)

tpl = "i am %(name)s age %(age)d" % {"name": "zhu", "age": 18}
print(tpl)

tpl = "percent %.2f" % 99.97623
print(tpl)

tpl = "i am %(pp).2f" % {"pp": 123.425556, }
print(tpl)

tpl = "i am %.2f%%" % 123.425556
print(tpl)

更多语法格式

%[(name)][flags][width].[precision]typecode
"""
(name)     可选,用于选择指定的key
Flags      可选,可供选择的值有:
   +        右对齐;正数前加正号,负数前加负号;
   -        左对齐;正数前无符号,负数前加负号;
   空格      右对齐;正数前加空格,负数前加负号;
   0        右对齐;正数前无符号,负数前加负号;
            用0填充空白处;
width       可选,占有宽度
.precision  可选,小数点后保留的位数
typecode    必选
"""

# typecode 有以下这些:
"""
s  获取传入对象的__str__方法的返回值,并将其格式化到指定位置
d  将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
f  将整数、浮点数转换成浮点数表示,并将其格式化到指定位置
   (默认保留小数点后6位)
o  将整数转换成 八  进制表示,并将其格式化到指定位置
x  将整数转换成十六进制表示,并将其格式化到指定位置
%  当字符串中存在格式化标志时,需要用 %%表示一个百分号
"""

2、str.format() 方式

In [111]: 'I am {}'.format('duan') 


tpl = "i am {}, age {}, {}"
r = tpl.format("tom", 18, 'man')
print(r)

tpl = "i am {}, age {}, {}"
r = tpl.format(*["tom", 18, 'man'])
print(r)
==========================================================
a, *b = ["tom", 18, 'man']
print(a)
print(b)
*b, a = ["tom", 18, 'ge']
print(a)
print(b)

tpl = "i am {0}, age {1}, really {0}"
print(tpl.format("tom", 18))


tpl = "i am {0}, age {1}, really {0}"
tpl.format(*["tom", 18])

tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(name="tom", age=18))
#
tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(**{"name": "tom", "age": 18}))

tpl = "i am {0[0]}, age {0[1]}, really {1[2]}"
print(tpl.format([1, 2, 3], [11, 22, 33]))

tpl = "i am {:s}, age {:d}, money {:f}"
print(tpl.format("seven", 18, 88888.1))

tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)

tpl = "i am {name:s}, age {age:d}"
tpl.format(name="xiguatian", age=18)

tpl = "i am {name:s}, age {age:d}"
tpl.format(**{"name": "xiguatian", "age": 18})

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}"
print(tpl.format(15, 15, 15, 15, 15, 15.87623, 2))

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X},\
      {0:.2%}"
print(tpl.format(15))

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},\
       {num:X}, {num:.2%}"
print(tpl.format(num=15))
print("{0:.3%}".format(0.15))

tpl = "{0:<6}---{0:<8}---{0:>13}"
print(tpl.format('123'))

更多语法格式

[[fill]align][#][0][width][,][.precision][type]

fill         【可选】空白处填充的字符
align        【可选】对齐方式(需配合width使用

#            【可选】对于二进制、八进制、十六进制,如果加上#,
              会显示 0b/0o/0x,否则不显示
              
,           【可选】为数字添加分隔符,如:1,000,000
width        【可选】格式化位所占宽度
.precision   【可选】小数位保留精度
type         【可选】格式化类型


"""
    
"""
type  【可选】格式化类型
传入" 字符串类型 “的参数
         s,格式化字符串类型数据
        空白,未指定类型,则默认是None,同s
传入“ 整数类型 "的参数  b,将10进制整数自动转换成2进制表示然后格式化
  c,将10进制整数自动转换为其对应的unicode字符
  d,十进制整数
  o,将10进制整数自动转换成8进制表示然后格式化;
  x,将10进制整数自动转换成16进制表示然后格式化(小写x)
  f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
  %,显示百分比(默认显示小数点后6位)

3、模板字符串(标准库)

这是Python中字符串格式化的另一个工具:模板字符串。它是一种更简单,功能更少的机制,但在某些情况下,这可能正是您所需要的。

我们来看一个简单的示例:

In [114]: from string import Template                                                

In [115]: name='duan'                                                                

In [116]: s=Template('hello $name')                                                  

In [117]: print(s.substitute(name=name))                                             
hello duan

4、 f-string方式

f-string 也称为 格式化的字符串文字,是以f 或 F 为前缀的字符串文字。

这些字符串可能包含可被替换的字段,这些字段是由大括号 {} 分隔的表达式。

虽然其他字符串文字总是具有常量值,但格式化字符串实际上是在运行时计算的表达式。

语法

语法类似于 str.format() 的语法,但是你发现 str.formate() 方式有时候不是那么简洁。比如在一个有够多的变量需要替换时,就显得非常的臃长且不易读。

In [119]: name='duan'                                                                

In [120]: age='18'                                                                   

In [121]: a=f'hello {name},your age {age}'                                           

In [122]: a                                                                          
Out[122]: 'hello duan,your age 18'

相关文章

网友评论

      本文标题:七、格式化输出

      本文链接:https://www.haomeiwen.com/subject/luudactx.html