gpt4 book ai didi

python - 什么是打印(f“...”)

转载 作者:行者123 更新时间:2023-12-04 04:27:33 25 4
gpt4 key购买 nike

我正在阅读一个 python 脚本,它接受 XML 文件的输入并输出一个 XML 文件。但是,我不明白打印语法。有人可以解释一下fprint(f"...")做?

args = parser.parser_args()

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

最佳答案

f 表示 Formatted string literals 并且它是 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.



格式化字符串文字的一些示例:
>>> 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

关于python - 什么是打印(f“...”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com