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)
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)
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
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)
要按顺序打印元素,请使用{}而不指定索引
print('[{},{},{}]'.format(1,2,3))
Run Code Online (Sandbox Code Playgroud)
(从python 2.7和python 3.1开始工作)
归档时间: |
|
查看次数: |
89082 次 |
最近记录: |