相关疑难解决方法(0)

1320
推荐指数
13
解决办法
37万
查看次数

python格式字符串未使用的命名参数

比方说我有:

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)

是否有一些解决方法可以防止此错误发生,例如:

  • 如果keyrror:忽略,别管它(但要解析别人)
  • 比较格式字符串和可用的命名参数,如果缺少则添加

python string string-formatting missing-data defaultdict

48
推荐指数
5
解决办法
2万
查看次数

如何让Python优雅地格式化None和不存在的字段

如果我用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)

当然,理想情况下,我希望能够指定使用的字符串而不是那些缺少的值.

python string-formatting missing-data

28
推荐指数
3
解决办法
2万
查看次数

Python替换,使用数组中的模式

我需要使用数组替换字符串中的一些东西,它们看起来像这样:

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 regex arrays replace

3
推荐指数
1
解决办法
3125
查看次数