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?
To print elements sequentially use {} without specifying the index
print('[{},{},{}]'.format(1,2,3))
(works since python 2.7 and python 3.1)
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]"
Before answering this question please go through couple of articles given below:
Python Official Docs here
Useful article:
Now let's answer this question
Question: 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?
Answer:
Well this is certainly a one-line code answer which is
print("[{0},{1},{2}]".format(1, 2, 3))
When you execute this one-line code a list containing three values as [1, 2, 3]
will be printed. I hope this was pretty simple and self-explanatory.
Thanks
Tanu
You have lot of solutions :)
simple way (C-style):
print("[%i, %i, %i]" %(1, 2, 3))
Use str.format()
print("[{0}, {1}, {2}]", 1, 2, 3)
Use str.Template()
s = Template('[$a, $b, $c]')
print(s.substitute(a = 1, b = 2, c = 3))
You can read PEP 3101 -- Advanced String Formatting
If you don't know how many items are in list, this aproach is the most universal
>>> '[{0}]'.format(', '.join([str(i) for i in [1,2,3]]))
'[1, 2, 3]'
It is mouch simplier for list of strings
>>> '[{0}]'.format(', '.join(['a','b','c']))
'[a, b, c]'
Very short answer.
example: print("{:05.2f}".format(2.5163)) returns 02.51