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?
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?
If you don't know how many items are in list, this aproach is the most universal
It is mouch simplier for list of strings
The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:
http://docs.python.org/library/string.html#formatstrings
Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:
To print elements sequentially use {} without specifying the index
(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 offormat
.You can now do:
Common other uses I find useful are:
Which will produce:
Very short answer.
example: print("{:05.2f}".format(2.5163)) returns 02.51
You can do it three ways:
Use Python's automatic pretty printing:
Showing the same thing with a variable:
Use 'classic' string substitutions (ala C's printf). Note the different meanings here of % as the string-format specifier, and the % to apply the list (actually a tuple) to the formatting string. (And note the % is used as the modulo(remainder) operator for arithmetic expressions.)
Note if we use our pre-defined variable, we'll need to turn it into a tuple to do this:
Use Python 3 string formatting. This is still available in earlier versions (from 2.6), but is the 'new' way of doing it in Py 3. Note you can either use positional (ordinal) arguments, or named arguments (for the heck of it I've put them in reverse order.
Note the names 'one' ,'two' and 'three' can be whatever makes sense.)