x = " \{ Hello \} {0} "
print x.format(42)
Run Code Online (Sandbox Code Playgroud)
给我 : Key Error: Hello\\
我想打印输出: {Hello} 42
比方说我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
Run Code Online (Sandbox Code Playgroud)
这个输出:
'bond, james bond'
Run Code Online (Sandbox Code Playgroud)
接下来我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
Run Code Online (Sandbox Code Playgroud)
这将输出:
KeyError: 'james'
Run Code Online (Sandbox Code Playgroud)
是否有一些解决方法可以防止此错误发生,例如:
如果我用Python写:
data = {'n': 3, 'k': 3.141594, 'p': {'a': 7, 'b': 8}}
print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
del data['k']
data['p']['b'] = None
print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
Run Code Online (Sandbox Code Playgroud)
我明白了:
3, 3.14, 7, 8
Traceback (most recent call last):
File "./funky.py", line 186, in <module>
print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
KeyError: 'k'
Run Code Online (Sandbox Code Playgroud)
而不是错误消息,我如何让Python更优雅地格式化None和不存在的字段?
举个例子,我想在输出中看到更像:
3, 3.14, 7, 8
3, ~, 7, ~
Run Code Online (Sandbox Code Playgroud)
当然,理想情况下,我希望能够指定使用的字符串而不是那些缺少的值.
我需要使用数组替换字符串中的一些东西,它们看起来像这样:
array = [3, "$x" , "$y", "$hi_buddy"]
#the first number is number of things in array
string = "$xena is here $x and $y."
Run Code Online (Sandbox Code Playgroud)
我有另外一个数组有东西来替换那些东西,让我们说它叫做rep_array.
rep_array = [3, "A", "B", "C"]
Run Code Online (Sandbox Code Playgroud)
对于替换我使用这个:
for x in range (1, array[0] + 1):
string = string.replace(array[x], rep_array[x])
Run Code Online (Sandbox Code Playgroud)
但结果是:
string = "Aena is here A and B."
Run Code Online (Sandbox Code Playgroud)
但是我需要的只是孤独的$ x而不是$ x.结果应如下所示:
string = "$xena is here A and B."
Run Code Online (Sandbox Code Playgroud)
注意:
array开始的所有模式$.$,模式匹配; $xena不匹配$x,但foo$x 会匹配. …python ×4
missing-data ×2
string ×2
arrays ×1
curly-braces ×1
defaultdict ×1
format ×1
regex ×1
replace ×1