python格式化函数format

format功能

格式(填充)对齐,可以格式化任何对象,包括字符串,数值等

#format函数会return字符串结果,但不会打印

# 1. 格式化填充单个对象


print( format(text, '=>20s') )
#  '=========Hello World' 
# =:符号填充
# > 内容右对齐, < 左对齐, ^ 居中
# 20:字符串总长度控制
# s:以字符串类型打印输出,f:浮点数,,d:整数


# 2.同时格式化多个对象

'{:>10s} {:>10s}'.format('Hello', 'World')
#  "Hello World"
#  format作用于单个字符串**,串内可以格式化多个数据,多个数据分别用{}包裹
#  {  }内部:后放**填充位置参数,数据截断进度,填充符号,字符总长度控制参数等;  
#  : 前没什么用,随便写不写都行

"{} {}".format("hello", "world")    # 不设置指定位置,默认按顺序对应输出
# 'hello world'



# 3.格式化数字

x = 1.2345
format(x, '>10')
# ' 1.2345'
format(x, '^10.2f')
# ' 1.23 '



# 旧的格式化输出方法%(仅能格式化字符串类型)

import math
print('The value of pi is approximately %5.3f.' % math.pi)
# The value of pi is approximately 3.142.
# " %"中的 %变量占位符 会被 后面%符号 后的数值填充
原文地址:https://www.cnblogs.com/Henry-ZHAO/p/13936057.html