String formatting in Python

余生长醉 提交于 2019-11-26 08:43:38

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]
Peter

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

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

To print elements sequentially use {} without specifying the index

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

(works since python 2.7 and python 3.1)

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)

I think that this combination is missing :P

"[{0}, {1}, {2}]".format(*[1, 2, 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

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]"

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]'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!