我想做类似于String.Format("[{0}, {1}, {2}]", 1, 2, 3)
的操作,返回结果应该是:
[1, 2, 3]
我该如何在Python中实现这个?
我想做类似于String.Format("[{0}, {1}, {2}]", 1, 2, 3)
的操作,返回结果应该是:
[1, 2, 3]
我该如何在Python中实现这个?
之前的答案使用了%格式化,在Python 3.0+中已经被淘汰。假设你在使用Python 2.6+,这里描述了一种更加面向未来的格式化系统:
http://docs.python.org/library/string.html#formatstrings
虽然还有更高级的功能,但最简单的形式看起来与你写的非常相似:
>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
使用Python的自动美化打印:
print [1, 2, 3] # Prints [1, 2, 3]
用一个变量展示相同的东西:
numberList = [1, 2]
numberList.append(3)
print numberList # Prints [1, 2, 3]
使用“经典”字符串替换(即C语言的printf函数)。请注意,这里的%具有不同的含义:一个是字符串格式指示符,另一个是用于将列表(实际上是元组)应用于格式化字符串的占位符。(还要注意,%在算术表达式中被用作取模(求余)运算符。)print "[%i, %i, %i]" % (1, 2, 3)
请注意,如果我们使用预定义变量,我们需要将其转换为元组才能执行此操作:
print "[%i, %i, %i]" % tuple(numberList)
使用Python 3字符串格式化。这在早期版本(从2.6开始)仍然可用,但在Py 3中是“新”的做法。请注意,您可以使用位置(序数)参数或命名参数(为了好玩,我将它们倒序排列)。print "[{0}, {1}, {2}]".format(1, 2, 3)
请注意,名称“one”,“two”和“three”可以是任何有意义的名称。
print "[{one}, {two}, {three}]".format(three=3, two=2, one=1)
print "[%(one)i, %(two)i, %(three)i]" % {'three':3,'two':2,'one':1}
。 - DrAlprint "[%s, %s, %s]" % (1, 2, 3)
要获取完整的参考文档,请查看此处: http://docs.python.org/library/stdtypes.html#string-formatting
PEP 498是Python 3.6
中新增的文本字符串插值方式,它基本上是format
的缩写形式。
现在您可以这样做:
f"[{1}, {2}, {3}]"
我觉得常见的其他有用用途包括:
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}]"""
这将生成:
"[1,\n 2,\n '3',\n 3.14,\n February 03, 2018]"
要按顺序打印元素,请使用{}而不需要指定索引。
print('[{},{},{}]'.format(1,2,3))
(适用于Python 2.7和Python 3.1及以上版本)
您的表述不太清晰,但我猜测您想要找的是:
foo = "Hello"
bar = "world"
baz = 2
print "%s, %s number %d" % (foo, bar, baz)
"[{0}, {1}, {2}]".format(*[1, 2, 3])
print("[%i, %i, %i]" %(1, 2, 3))
print("[{0}, {1}, {2}]", 1, 2, 3)
s = Template('[$a, $b, $c]')
print(s.substitute(a = 1, b = 2, c = 3))
非常简短的答案。
示例: print("{:05.2f}".format(2.5163)) 返回 02.51
f"[{1}, {2}, {3}]"
来格式化字符串。 - Soorena