python字符格式化

使用%格式化字符串

字符串格式化使用格式化操作符即百分号。

在%号的左侧放置一个字符串(格式化字符串),而右侧则放置希望格式化的值。

In [17]: name = "wxz"

In [18]: print "my name is %s" % name
my name is wxz

基本的转换说明符保护以下部分:

  • %字符:标记转换说明符的开始
  • 转换标志(可选):-表示左对齐;+表示在转换值前加上正负号;“”(空白)表示正数之前保留空格;0表示转换值位数不够用0填充。
  • 最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是,则宽度会从值元素中读出。
  • 点(.)后跟随精度值(可选):如果是实数则表示小数点后的位数,如果是字符串,则表示最大宽度。
  • 转换类型(常用的)

    %d: 表示带符号的十进制整数

    %s:表示使用str替换任意python对象

    %f:表示十进制浮点数

In [27]: "%10f" % pi        #宽度为10
Out[27]: '  3.141593'

In [28]: "%10.2f" % pi     #宽度为10,精度为2
Out[28]: '      3.14'

In [29]: "%010.2f" % pi    #宽度为10,精度为2,用0填充
Out[29]: '0000003.14'

In [30]: "%-10.2f" % pi    # 左对齐
Out[30]: '3.14      '

In [31]: "%+10.2f" % pi    # 在实数前面加上正负号
Out[31]: '     +3.14'

使用.format格式化

format是一种格式化函数,它通过{}和:来代替%。

通过位置代替

In [190]: "{0},{1}".format("hello","world")   ####位置指的是format中参数的位置
Out[190]: 'hello,world'

In [191]: "{1},{0}".format("hello","world")
Out[191]: 'world,hello'

In [192]: "{1},{0}".format("world","hello")
Out[192]: 'hello,world'

In [193]: "{1},{0},{1}".format("world","hello")  
Out[193]: 'hello,world,hello'

通过关键字参数

In [195]: "{age},{name}".format(age=21,name="wxz")
Out[195]: '21,wxz'

In [196]: "{name},{age}".format(age=21,name="wxz")
Out[196]: 'wxz,21'

注意python的版本不同,使用格式略有差异

In [11]: "{},{}".format("hello","world")        ####省略位置的指明则按默认参数顺序显示
Out[11]: 'hello,world'

In [12]: "{},{}".format("world","hello")
Out[12]: 'world,hello'
##若在python2.6版本中执行,必须明确制定其位置
In [200]: "{0},{1}".format("hello","world")
Out[200]: 'hello,world'

还可以通过列表,元组等的下标访问。

In [32]: greet = ["Welcome", "to", "NEWYORK"]

In [33]: "{0[0]},{0[1]},{0[2]}".format(greet)
Out[33]: 'Welcome,to,NEWYORK'

In [34]: city = ["HK", "Beijing"]

In [35]: "{0[0]},{0[1]},{1[1]}".format(greet,city)   # 注意使用方法
Out[35]: 'Welcome,to,Beijing'

In [37]: "{0[0]},{0[1]},{1[0]}".format(greet,city)
Out[37]: 'Welcome,to,HK'

#格式限定符
#它有着丰富的的“格式限定符”(语法是{}中带:号),比如:

#填充与对齐
#填充常跟对齐一起使用
#^、<、>分别是居中、左对齐、右对齐,后面带宽度
#:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

#比如,环境为python2.6
In [210]: "{0:>}".format("32")   ###这两个都为右对齐,注意宽度。
Out[210]: '32'

In [211]: "{0:>9}".format("32")
Out[211]: '       32'
#python2.7中可以如下表示
In [13]: "{:>}".format("43")
Out[13]: '43'

In [14]: "{:>5}".format("43")
Out[14]: '   43'

精度与类型

#精度经常与float类型一起使用
In [16]: "{:.3f}".format(3.1415926)
Out[16]: '3.142'

In [18]: "{:b}".format(15) ######二进制格式化
Out[18]: '1111'

In [19]: "{:d}".format(15)  #####十进制格式化
Out[19]: '15'

In [20]: "{:o}".format(15)  ####八进制格式化
Out[20]: '17'

In [21]: "{:x}".format(15)  ####十六进制格式化
Out[21]: 'f'

货币金额表示

In [23]: "{:,}".format(9651223456)
Out[23]: '9,651,223,456'
原文地址:https://www.cnblogs.com/wxzhe/p/8821003.html