python格式化方式

**python的格式化方式有下面三种:

  1. f with {expression}
  2. str.format()
  3. print-style format**
    下面将通过代码的形式进行展示:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# https://docs.python.org/3.6/tutorial/inputoutput.html#input-and-output
def str_and_repr():
    s = 'Hello world'
    print(str(s))   # Hello world
    print(repr(s))  # 'Hello world'
    print(str(1/7))
    print(repr(1/7))
# f with {expression}
def formatted_string_literals():
    import math
    # 3.142
    print(f'The value of pi is approximately {math.pi:.3f}')
    animals = 'eels'
    # My hovecraft is full of eels.
    print(f'My hovecraft is full of {animals}.')
    # My hovecraft is full of 'eels'. !r applies repr()
    print(f'My hovecraft is full of {animals!r}.')
# str.format
def str_format():
    # We are the knights who say "Ni!"
    print('We are the {} who say "{}!"'.format('knights', 'Ni'))
    # spam and eggs
    print('{0} and {1}'.format('spam', 'eggs'))
    # eggs and spam
    print('{1} and {0}'.format('spam', 'eggs'))
    # This spam is absolutely horrible.
    print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
    # 下面两种方式都是一样的效果
    table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
    print('Sjoerd: {0[Sjoerd]:d}, Jack: {0[Jack]:d}, Dcab: {0[Dcab]:d}'.format(table))
    print('Sjoerd: {Sjoerd:d}, Jack: {Jack:d}, Dcab: {Dcab:d}'.format(**table))
# print-style format
# https://docs.python.org/3.6/library/stdtypes.html#old-string-formatting
def print_format():
    import math
    # The vale of pi is approximately 3.142.
    print('The vale of pi is approximately %.3f.' %math.pi)
if __name__ == '__main__':
    # str_and_repr()
    # formatted_string_literals()
    # str_format()
    print_format()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值