Python中的字符串格式

Joa*_*nge 31 python string formatting

我想做一些类似的String.Format("[{0}, {1}, {2}]", 1, 2, 3)回报:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

我如何在Python中执行此操作?

DNS*_*DNS 61

之前的答案使用了%格式,这在Python 3.0+中逐步淘汰.假设您使用的是Python 2.6+,这里描述了一个更具前瞻性的格式化系统:

http://docs.python.org/library/string.html#formatstrings

虽然还有更多高级功能,但最简单的形式最终看起来非常接近您所写的内容:

>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

  • 此外,在Python 3.1中,没有必要指定序数."[{},{},{}]".format(1,2,3) (18认同)
  • 在2.7中,序数也是可选的 (8认同)
  • @Day 根据 Python 3.0 What's New 文档 (http://docs.python.org/release/3.0/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting):“ % 运算符仍然受支持;它将在 Python 3.1 中被弃用,并在稍后的时间从该语言中删除。” 鉴于 % 的受欢迎程度,也许这实际上不会发生,但至少这是需要注意的事情。 (2认同)

Pet*_*ter 27

你可以用三种方式做到:


使用Python的自动漂亮打印:

print [1, 2, 3]   # Prints [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

用变量显示相同的东西:

numberList = [1, 2]
numberList.append(3)
print numberList   # Prints [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

使用'经典'字符串替换(ala C的printf).请注意%的不同含义是字符串格式说明符,%是将列表(实际上是元组)应用于格式化字符串.(注意%用作算术表达式的模(余数)运算符.)

print "[%i, %i, %i]" % (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

请注意,如果我们使用预定义的变量,我们需要将其转换为元组来执行此操作:

print "[%i, %i, %i]" % tuple(numberList)
Run Code Online (Sandbox Code Playgroud)

使用Python 3字符串格式.这仍然可以在早期版本中使用(从2.6开始),但它是在Py 3中执行此操作的"新方法".注意,您可以使用位置(序数)参数或命名参数(对于它我已经把它放了它们的顺序相反.

print "[{0}, {1}, {2}]".format(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

注意名字'one','two'和'three'可以是任何有意义的.)

print "[{one}, {two}, {three}]".format(three=3, two=2, one=1)
Run Code Online (Sandbox Code Playgroud)

  • 为了完整,使用"经典"风格,你也可以:`print"[%(one)i,%(two)i,%(three)i]"%{'three':3,'two': 2, '一个':1}` (4认同)

chi*_*s42 18

你正在寻找字符串格式,在python中它是基于C中的sprintf函数.

print "[%s, %s, %s]" % (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

有关完整参考,请访问:http: //docs.python.org/library/stdtypes.html#string-formatting

  • 谢谢,最后一个%是什么意思?另外,您是否必须像 C++ 中那样用 s、d、f 等来编写应该打印的类型? (2认同)

too*_*ays 10

PEP 498 增加了python 3.6文字字符串插值,这基本上是format.

您现在可以执行以下操作:

f"[{1}, {2}, {3}]"
Run Code Online (Sandbox Code Playgroud)

我发现有用的常见其他用途是:

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}]"""
Run Code Online (Sandbox Code Playgroud)

这将产生:

"[1,\n     2,\n     '3',\n      3.14,\n     February 03, 2018]"
Run Code Online (Sandbox Code Playgroud)


Ric*_*lli 5

要按顺序打印元素,请使用{}而不指定索引

print('[{},{},{}]'.format(1,2,3))
Run Code Online (Sandbox Code Playgroud)

(从python 2.7和python 3.1开始工作)