【发布时间】:2010-10-05 18:21:58
【问题描述】:
我想做类似String.Format("[{0}, {1}, {2}]", 1, 2, 3) 的事情,它会返回:
[1, 2, 3]
如何在 Python 中做到这一点?
【问题讨论】:
-
在python 3.6+你可以使用
f"[{1}, {2}, {3}]"
标签: python string formatting
我想做类似String.Format("[{0}, {1}, {2}]", 1, 2, 3) 的事情,它会返回:
[1, 2, 3]
如何在 Python 中做到这一点?
【问题讨论】:
f"[{1}, {2}, {3}]"
标签: python string formatting
您的自我表述并不十分值得称道,但我大胆猜测一下,这就是您要找的东西:
foo = "Hello"
bar = "world"
baz = 2
print "%s, %s number %d" % (foo, bar, baz)
【讨论】:
您正在寻找字符串格式,它在 python 中基于 C 中的 sprintf 函数。
print "[%s, %s, %s]" % (1, 2, 3)
完整的参考请看这里: http://docs.python.org/library/stdtypes.html#string-formatting
【讨论】:
之前的答案使用了 % 格式,在 Python 3.0+ 中将逐步淘汰。假设您使用的是 Python 2.6+,这里描述了一个更面向未来的格式化系统:
http://docs.python.org/library/string.html#formatstrings
虽然还有更高级的功能,但最简单的形式最终看起来非常接近您编写的内容:
>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
【讨论】:
format 方法是首选,但并没有说 % 运算符正在逐步淘汰。
你可以通过三种方式做到这一点:
使用 Python 的自动漂亮打印:
print [1, 2, 3] # Prints [1, 2, 3]
用变量表示同样的东西:
numberList = [1, 2]
numberList.append(3)
print numberList # Prints [1, 2, 3]
使用“经典”字符串替换(ala 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)
注意名称“一”、“二”和“三”可以是任何有意义的名称。)
print "[{one}, {two}, {three}]".format(three=3, two=2, one=1)
【讨论】:
print "[%(one)i, %(two)i, %(three)i]" % {'three':3,'two':2,'one':1}
要按顺序打印元素,请使用 {} 而不指定索引
print('[{},{},{}]'.format(1,2,3))
(从 python 2.7 和 python 3.1 开始工作)
【讨论】:
如果你不知道列表中有多少项,这种方法是最通用的
>>> '[{0}]'.format(', '.join([str(i) for i in [1,2,3]]))
'[1, 2, 3]'
字符串列表更简单
>>> '[{0}]'.format(', '.join(['a','b','c']))
'[a, b, c]'
【讨论】:
我认为缺少这种组合:P
"[{0}, {1}, {2}]".format(*[1, 2, 3])
【讨论】:
你有很多解决方案:)
简单方式(C 风格):
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))
【讨论】:
位于python 3.6 的PEP 498 添加了文字字符串插值,基本上是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("{:05.2f}".format(2.5163)) 返回 02.51
【讨论】:
【讨论】:
由于python-3.6,Python 支持literal string interpolation [pep-498]。因此,您可以使用字符串的 f 前缀进行格式化。例如:
x = 1
y = 2
z = 3
f'[{x}, {y}, {z}]'
这会产生:
>>> f'[{x}, {y}, {z}]'
'[1, 2, 3]'
在问题中的 C#(String.Format(…) 的语言)中,由于c#-6.0、string interpolation [microsof-tdoc] 也受支持,例如:
int x = 1;
int y = 2;
int z = 3;
string result = $"[{x}, {y}, {z}]";
例如:
csharp> int x = 1;
csharp> int y = 2;
csharp> int z = 3;
csharp> $"[{x}, {y}, {z}]";
"[1, 2, 3]"
【讨论】: