Python 字符串格式化输出方式

python学习网 2018-09-08 07:51:02

字符串格式化有两种方式:百分号方式、format方式。

其中,百分号方式比较老,而format方式是比较先进的,企图替代古老的方式,目前两者共存。

1、百分号方式

格式:%[(name)][flags][width].[precision]typecode

  • (name)    可选,用于选择指定的key
  • flags        可选,可供选择的值有:
    • + 右对齐:正数的加正号,负数的加负号
    • - 左对齐:正数前没有负号,负数前加负号
  • width    可选,占有宽度
  • .precision    可选,小数点后保留的位数
  • typecode     必选
    • s,获取传入的对象__str__方法的返回值,并将其格式化到指定位置
    • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
    • c,整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <=1114111
    • o,将整数转换成八进制表示,并将其格式化到指定位置
    • x,将整数转换成16进制,并将其格式化到指定位置
    • d,将整数,浮点数转化为十进制表示,并将其格式化到指定位置

例子:

>>> s = 'hello, %s!' % 'python'
>>> s
'hello, python!'

>>> s = 'hello, %s, %d!' % ('python', 2018)
>>> s
'hello, python, 2018!'

>>> s = 'hello, %(name)s, %(year)d!' % {'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018!'

>>> s = 'hello, %(name)+10s, %(year)-10d!' % {'name': 'python', 'year': 2018}
>>> s
'hello,     python, 2018      !'

>>> s = 'hello, %(name)s, %(year).3f!' % {'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018.000!'

 2、format方式

>>> s = 'hello, {}, {}'.format('python', 2018)
>>> s
'hello, python, 2018'

>>> s = 'hello, {0}, {1}, hi, {0}'.format('python', 2018)
>>> s
'hello, python, 2018, hi, python'

>>> s = 'hello, {name}, {year}, hi, {name}'.format(name='python', year=2018)
>>> s
'hello, python, 2018, hi, python'

>>> s = 'hello, {:s}, {:d}, hi, {:f}'.format('python', 2018, 9.7)
>>> s
'hello, python, 2018, hi, 9.700000'

 

阅读(3048) 评论(0)