Python字符串format()函数讲解

format() 函数用来收集其后的位置参数和关键字段参数,并用他们的值填充字符串中的占位符。通常格式如下:

"{pos or key : fill, align, sign, 0, width, .precision, type}".format(para1...)
  • 整个 花括号 是一个占位符
  • 冒号前 的 pos 或者 key 用来定位 format() 函数的参数
  • 冒号后 的位置用来将该参数格式化,其中每一个都是可选项
  1. \color{#0000FF}{fill} 用来指定填充字符,默认为空格

  2. \color{#0000FF}{align} 指定对齐方式:\color{#9932CC}{>} 为右对齐,\color{#9932CC}{<} 为左对齐,^ 为居中对齐

  3. \color{#0000FF}{sing} 指定是否保留正负号:\color{#9932CC}{+} 保留正号,\color{#9932CC}{-} 保留负号

  4. \color{#0000FF}{width} 宽度(前面如果加 0 ,则表示用 0 填充)

  5. \color{#0000FF}{width} 指定宽度

  6. \color{#0000FF}{precision} 指定精确度

  7. \color{#0000FF}{type} 指定类型,\color{#9932CC}{b} 二进制,\color{#9932CC}{o} 八进制,\color{#9932CC}{d} 十进制,\color{#9932CC}{x} 十六进制,\color{#9932CC}{f} 浮点型

示例:
使用位置进行填充
print("Hello,{}. My name is {}. How is going? ".format("Hialry", "Vergil"))
# Hello,Hialry. My name is Vergil. How's it going?
若格式中未指定填充位置,将会按序填充
print("{}  {}  {}  {}  {}  {}".format("1","2","3","4","5","6"))
# 1  2  3  4  5  6

print("{0}  {1}  {3}  {5}  {2}  {4}".format("1","2","3","4","5","6"))
# 1  2  4  6  3  5
使用关键字段进行填充
print(
    "I\'m {name1} ,and I miss u so much,{name2}.".format(
        name1="Vergil",
        name2="Hilary"))
# I'm Vergil ,and I miss u so much,Hilary.      
使用下标填充
names=['Hilary','Vergil','Nero']
places=['Chengdu','Shijiazhuang','Tokyo']
print(
    "Hi {names[0]}.I am {names[1]} and this is {names[2]}.".format(
        names=names))
# Hi Hilary.I am Vergil and this is Nero.

print(
    "Three people:{0[0]},{0[1]},{0[2]} from three places:{1[0]},{1[1]},{1[2]}.".format(
        names,
        places))
# Three people:Hilary,Vergil,Nero from three places:Chengdu,Shijiazhuang,Tokyo.
进制转换
print("{0:b},{0:o},{1:d},{1:x}".format(256, 512))
# 100000000,400,512,200
逗号分隔
print("{:,}".format(123456789))
# 123,456,789
浮点数格式
print("{:+12.3f}".format(3.14159265358979))
# +3.142
对齐与填充, \n 换行符

提示:“ 对齐 ” 指数据本身,而非与 上下行的其他数据 对齐

print(
    "{:>010}\n".format(12),                 # 右对齐,填充0,宽度10
    "{:0>10}\n".format(12),                 # 填充0,右对齐,宽度10
    "{:x>10}\n".format(12),                 # 填充0,右对齐,宽度10
    "{:0<+12.3f}\n".format(-12.34567),      # 填充0,左对齐,保留+号,宽度12,保留3位小数
    "{:^10}\n".format(3)                    # 居中对齐,宽度10
)
'''
0000000012
 0000000012
 -12.34600000
     3   
'''
        #  以上 print 结果,第 2 行开始多了一个空格,原因未知
print("{:>010}".format(12))
print("{:0>5}".format(12))
print("{:x>6}".format(12))
print("{:x<6}".format(12))
print("{:x^6}".format(12))
print("{:0<+12.3f}".format(-12.34567))
print("{:^10}".format(3) )
'''
0000000012
00012
xxxx12
12xxxx
xx12xx
-12.34600000
    3   
'''

笔记参考:https://blog.csdn.net/Hilavergil/article/details/79161590
文档参考:http://www.runoob.com/python/att-string-format.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。