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?
JavaScript
x
5
1
args = parser.parser_args()
2
3
print(f"Input directory: {args.input_directory}")
4
print(f"Output directory: {args.output_directory}")
5
Advertisement
Answer
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:
JavaScript
1
25
25
1
>>> name = "Fred"
2
>>> f"He said his name is {name}."
3
"He said his name is Fred."
4
5
>>> name = "Fred"
6
>>> f"He said his name is {name!r}."
7
"He said his name is Fred."
8
9
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
10
"He said his name is Fred."
11
12
>>> width = 10
13
>>> precision = 4
14
>>> value = decimal.Decimal("12.34567")
15
>>> f"result: {value:{width}.{precision}}" # nested fields
16
result: 12.35
17
18
>>> today = datetime(year=2017, month=1, day=27)
19
>>> f"{today:%B %d, %Y}" # using date format specifier
20
January 27, 2017
21
22
>>> number = 1024
23
>>> f"{number:#0x}" # using integer format specifier
24
0x400
25