栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】format格式化函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】format格式化函数

基本语法是通过 {} 和 : 来代替以前的 % 。

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
保留小数点后两位
>>> r = 3.141592
>>>> print("{:.2f}".format(r))
3.14
填充&对齐
  • <左对齐
  • >右对齐
  • ^居中对齐
  • : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
数字补x (填充左边, 宽度为5)
>>> n = 6
>>> print("{:x>5d}".format(n))
xxxx6
数字补x (填充右边, 宽度为5)
>>> n = 60
print("{:x<5d}".format(n))
60xxx
对齐 (宽度为7)
>>> n = 81
>>> print("{:<7d}".format(n))
81     
>>> print("{:>7d}".format(n))
     81
>>> print("{:^7d}".format(n))
  81   
进制

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

'{:b}'.format(11) #1011
'{:d}'.format(11) #11
'{:o}'.format(11) #13
'{:x}'.format(11) #b
'{:#x}'.format(11) #0xb
'{:#X}'.format(11) #0XB
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290702.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号