Python format内置函数

普通用法

'{} {}'.format('hello', 'world')    # hello world
'{1} {0}'.format('world', 'hello')  # hello world

数字的格式化输出

# 数字的格式化输出
x = 1234.5678
format(x, '.2f')       # 1234.57
format(x, '>10.2f')    # "   1234.57"
format(x, '^10.2f')    # " 1234.57  "
format(x, ',')         # 1,234.5678
format(x, '^10,.2f')   # " 1,234.57 "
'{:^10.2f}'.format(x)  # " 1234.57  "

根据变量名格式化

website_name = '百度'
website_url = 'www.baidu.com'
# 输出:百度 www.baidu.com
f"{website_name} {website_url}"  # python3.6新增f-string方法
"{website_name} {website_url}".format(website_name=website_name, website_url=website_url)

利用字典格式化输出

website_dic = {'website': '百度', 'url': 'www.baidu.com'}
'{website} {url}'.format(**website_dic)  # 百度 www.baidu.com

填充和对齐操作

format('hello', '^20')    # 居中 "       hello        "
format('hello', '>20')    # 不足位,左填充 "               hello"
format('hello', '<20')    # 不足位,右填充 "hello               "

'{:^20}'.format('hello')  # 居中 "       hello        "
'{:>20}'.format('hello')  # 不足位,左填充 "               hello"
'{:<20}'.format('hello')  # 不足位,右填充 "hello               "

format('hello', '=^20')   # 居中并填充 "=======hello========"
format('hello', '=>20')   # 不足位,左填充 ===============hello
format('hello', '=<20')   # 不足位,右填充 "hello==============="

进制转换

x = 1234
bin(x)  # 0b10011010010
oct(x)  # 0o2322
hex(x)  # 0x4d2
# 如果你不想输出0b, 0o, 0x的话,可以使用format
format(x, 'b')  # 10011010010
format(x, 'o')  # 2322
format(x, 'x')  # 4d2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值