I want to do something like String.Format(\"[{0}, {1}, {2}]\", 1, 2, 3)
which returns:
[1, 2, 3]
How do I do this in Python?>
PEP 498 which landed in python 3.6
added literal string interpolation, which is basically a shortened form of format
.
You can now do:
f"[{1}, {2}, {3}]"
Common other uses I find useful are:
pi = 3.141592653589793
today = datetime(year=2018, month=2, day=3)
num_2 = 2 # Drop assigned values in
num_3 = "3" # Call repr(), or it's shortened form !r
padding = 5 # Control prefix padding
precision = 3 # and precision for printing
f"""[{1},
{num_2},
{num_3!r},
{pi:{padding}.{precision}},
{today:%B %d, %Y}]"""
Which will produce:
"[1,\n 2,\n '3',\n 3.14,\n February 03, 2018]"