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
orF
. 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=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400