什么是打印(f“...") [英] What is print(f"...")

查看:147
本文介绍了什么是打印(f“...")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个 Python 脚本,该脚本接受 XML 文件的输入并输出一个 XML 文件.但是,我不明白打印语法.有人可以解释一下 print(f"...") 中的 f 是做什么的吗?

args = parser.parser_args()打印(f输入目录:{args.input_directory}")打印(f输出目录:{args.output_directory}")

解决方案

f 的意思是 格式化字符串文字,它是 Python 3.6 中的新内容.

<小时><块引用>

格式化字符串文字f-string 是一个字符串文字,它是以 'f''F' 为前缀.这些字符串可能包含替换字段,它们是由大括号 {} 分隔的表达式.尽管其他字符串文字总是有一个常量值,格式化的字符串实际上是在运行时计算的表达式.

<小时>

格式化字符串文字的一些示例:

<预><代码>>>>姓名 = "弗雷德">>>f他说他的名字是{name}."他说他叫弗雷德.">>>姓名 = "弗雷德">>>f他说他的名字是{name!r}."他说他叫弗雷德.">>>f他说他的名字是{repr(name)}."# repr() 等价于 !r他说他叫弗雷德.">>>宽度 = 10>>>精度 = 4>>>value = decimal.Decimal("12.34567")>>>f"result: {value:{width}.{precision}}" # 嵌套字段结果:12.35>>>今天 = 日期时间(年 = 2017,月 = 1,日 = 27)>>>f"{today:%B %d, %Y}" # 使用日期格式说明符2017 年 1 月 27 日>>>数字 = 1024>>>f"{number:#0x}" # 使用整数格式说明符0x400

I am reading through a python script that takes an input of XML files and outputs an XML file. However, I do not understand the printing syntax. Can someone please explain what f in print(f"...") does?

args = parser.parser_args()

print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")

解决方案

The f means Formatted string literals and it's new in Python 3.6.


A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.


Some examples of formatted string literals:

>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."

>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35

>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2017

>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400

这篇关于什么是打印(f“...")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆