Python字符串format()函数讲解

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

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

  2. 指定对齐方式: 为右对齐, 为左对齐,^ 为居中对齐

  3. 指定是否保留正负号: 保留正号, 保留负号

  4. 宽度(前面如果加 0 ,则表示用 0 填充)

  5. 指定宽度

  6. 指定精确度

  7. 指定类型, 二进制, 八进制, 十进制, 十六进制, 浮点型

示例:
使用位置进行填充
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

你可能感兴趣的:(Python字符串format()函数讲解)