format用法
f-string用法
%-formatting用法
print("字符串类型输出 第一种: %s" % "hello word")
print("整数类型输出 第一种: %d" % 0)
字符串类型输出 第一种: hello word
整数类型输出 第一种: 0
str.format()用法
相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
echo = "hello world"
num = 0
print("字符串类型输出 第二种:{}".format(echo))
print("整数类型输出 第二种: {}".format(num))
字符串类型输出 第二种:hello world
整数类型输出 第二种: 0
f-string用法
格式字符串包含用大括号括起来的“替换字段” {}
。大括号中未包含的任何内容都被视为文字文本,将原样复制到输出中。如果您需要在文字文本中包含大括号字符,可以通过加倍:{{
和来转义它}}
。Python3.6新增的一种字符串格式化方法,格式为f"{变量},用大括号{}标明被替换的字符,f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式:
echo = "hello world"
num = 0
print(f"字符串类型输出 第三种:{echo}")
print(f"整数类型输出 第三种: {num}")
字符串类型输出 第三种:hello world
整数类型输出 第三种: 0
对比
f-string: formatted string literals, 格式化字符串常量。
功能同%-formating, str.format(),操作方便,速度快