46

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?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • 6
    in [python 3.6+](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) you can use `f"[{1}, {2}, {3}]"` – Soorena Feb 03 '18 at 14:19

14 Answers14

76

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:

>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
DNS
  • 37,249
  • 18
  • 95
  • 132
  • 24
    Also, in Python 3.1, there's no need to specify the ordinals. "[{}, {}, {}]".format(1, 2, 3) – Jason R. Coombs Feb 04 '10 at 17:01
  • 10
    The ordinals are also optional in in Python 2.7 – marshall.ward Jul 28 '12 at 02:28
  • Do you have a reference which documents that % formatting is being phased out in Python 3.0+? It's still in 3.3 - see http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting - and while the docs say that the newer `format` method is preferred, it doesn't say that the % operator is being phased out. – Day Feb 08 '13 at 09:53
  • 2
    @Day According to the Python 3.0 What's New document (http://docs.python.org/release/3.0/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting): "the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time." Given the popularity of %, maybe this won't actually happen, but at least it's something to be aware of. – DNS Feb 08 '13 at 14:28
  • Percent formatting is still here, and the intent to remove it from the language seems to have been abandoned. – tripleee Jun 28 '20 at 15:19
32

You can do it three ways:


Use Python's automatic pretty printing:

print [1, 2, 3]   # Prints [1, 2, 3]

Showing the same thing with a variable:

numberList = [1, 2]
numberList.append(3)
print numberList   # Prints [1, 2, 3]

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.)

print "[%i, %i, %i]" % (1, 2, 3)

Note if we use our pre-defined variable, we'll need to turn it into a tuple to do this:

print "[%i, %i, %i]" % tuple(numberList)

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.

print "[{0}, {1}, {2}]".format(1, 2, 3)

Note the names 'one' ,'two' and 'three' can be whatever makes sense.)

print "[{one}, {two}, {three}]".format(three=3, two=2, one=1)
Schof
  • 6,329
  • 5
  • 28
  • 38
Peter
  • 401
  • 5
  • 7
  • 5
    For completeness, using the "classic" style, you can also do: `print "[%(one)i, %(two)i, %(three)i]" % {'three':3,'two':2,'one':1}` – DrAl Aug 10 '10 at 11:03
20

You're looking for string formatting, which in python is based on the sprintf function in C.

print "[%s, %s, %s]" % (1, 2, 3)

For a complete reference look here: http://docs.python.org/library/stdtypes.html#string-formatting

Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55
chills42
  • 14,201
  • 3
  • 42
  • 77
10

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]"
toofarsideways
  • 3,956
  • 2
  • 31
  • 51
8

To print elements sequentially use {} without specifying the index

print('[{},{},{}]'.format(1,2,3))

(works since python 2.7 and python 3.1)

Riccardo Galli
  • 12,419
  • 6
  • 64
  • 62
4

I think that this combination is missing :P

"[{0}, {1}, {2}]".format(*[1, 2, 3])
radeklos
  • 2,168
  • 21
  • 19
  • Without explaining what the splat does, this is just esoteric. It applies to anything which accepts a list, anyway. – tripleee Jun 28 '20 at 15:20
4

You haven't formulated yourself very commendably, but I'll venture a guess this is what you're looking for:

foo = "Hello"
bar = "world"
baz = 2
print "%s, %s number %d" % (foo, bar, baz)
JosefAssad
  • 4,018
  • 28
  • 37
  • Thanks, what does the last % signifies? Also do you have to write the type of the way it should be printed like in C++ with s, d, f, etc? – Joan Venge Feb 05 '09 at 18:58
  • I'll refer you to DNS' answer above which is superior: http://stackoverflow.com/questions/517355/string-formatting-in-python/517471#517471 – JosefAssad Feb 05 '09 at 19:43
3

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

RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34
2

Very short answer.

example: print("{:05.2f}".format(2.5163)) returns 02.51

  • {} Set here Variable
  • : Start Styling
  • 0 leading with zeroes, " " leading with whitespaces
  • 5 LENGTH OF FULL STRING (Point counts, 00.00 is len 5 not 4)
  • .2 two digit after point, with rounding.
  • f for floats
Pit
  • 21
  • 1
2

Before answering this question please go through couple of articles given below:

Python Official Docs here

Useful article:

  • Python String format() - here

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

Tanu
  • 31
  • 3
  • The focus of an answer lies on your content on this site. That should be focused first. Not recommending reading articles. You can of course link to them but better placed at the end of the answer or (if several concerns are explained) place it where it belongs to. – RobertS supports Monica Cellio Aug 27 '20 at 16:44
2

Since , Python supports literal string interpolation [pep-498]. You thus can format with an f prefix to the string. For example:

x = 1
y = 2
z = 3
f'[{x}, {y}, {z}]'

This then produces:

>>> f'[{x}, {y}, {z}]'
'[1, 2, 3]'

In C# (the language of the String.Format(…)) in the question, since , string interpolation [microsoft-doc] is supported as well, for example:

int x = 1;
int y = 2;
int z = 3;
string result = $"[{x}, {y}, {z}]";

For example:

csharp> int x = 1;
csharp> int y = 2;
csharp> int z = 3;
csharp> $"[{x}, {y}, {z}]";
"[1, 2, 3]"
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

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]'
Yupa
  • 11
  • 1
1

There are 3 ways.

"%" operator which is the original way:

x, y, z = 1, 2, 3

print("[%i, %i, %i]" % (x, y, z)) # [1, 2, 3]

"str.format()" since Python 2.6:

x, y, z = 1, 2, 3

print("[{0}, {1}, {2}]".format(x, y, z)) # [1, 2, 3]

"f-strings" since Python 3.6:

x, y, z = 1, 2, 3

print(f'[{x}, {y}, {z}]') # [1, 2, 3]
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
-1

There are several places where you can get answers, for example here and here.

There are lots of ways of formatting a string in python, like:

  1. Using the format() function, for example:
x = 'hello'
y = 'person'
xy = '{} {}'.format(x, y)
  1. Using f-strings, for example:
x = 'hello'
y = 'person'
xy = f'{x} {y}'