Python 字符串格式化输出方式

字符串格式化有两种方式:百分号方式、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!'

%r 与 %s 区别:

%r 用来做 debug 比较好,因为它会显示变量的原始数据(raw data),而其它的符号则是用来向用户显示输出的。

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> a = 'sunday'
>>> print("Today is %s" % a)
Today is sunday
>>> print("Today is %r" % a)
Today is 'sunday'  # 格式化部分用单引号输出

>>> from datetime import datetime
>>> d = datetime.now()
>>> print('%s' % d)
2018-09-10 08:52:00.769949
>>> print('%r' % d)
datetime.datetime(2018, 9, 10, 8, 52, 0, 769949)  # 可以看见与上面输出存在明显的区别

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'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值