Python的字符串格式压制/沉默keyerror / indexerror [英] python string format suppress/silent keyerror/indexerror

查看:900
本文介绍了Python的字符串格式压制/沉默keyerror / indexerror的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用python string.format,当缺少索引时不会引发异常,而是插入一个空字符串。

格式(hello = 2,error2 =success)
result =我是{错误}示例字符串{error2}

在这里,结果应该是:

 我是一个成功的字符串成功

现在,python抛出一个keyerror并停止格式化。是否有可能改变这种行为?



谢谢

编辑:

存在Template.safe_substitute(甚至会使模式完好无损,而不是插入空字符串),但不能为string.format类似。 >期望的行为类似于PHP中的字符串替换。
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ get_value(self,key,args,kwargs):
try:
如果hasattr(key,__mod__):
返回args [key]
else:
return kwargs [key]
除外:
return

提供所需的行为。

解决方案

str.format()期望映射对象。试试这个:

pre $ from集合import defaultdict
$ bd = defaultdict(str)
d ['错误2'] =成功
s =我是一个{0 [错误]}示例字符串{0 [错误2]}
打印s.format(d)

$ b

您使用返回的 str()工厂制作defaultdict。然后你为defaultdict做一个键。在格式字符串中,您可以访问传递的第一个对象的键。这样做的好处是允许你传递其他的键和值,只要你的defaultdict是第一个参数 format()



另请参阅 http://bugs.python.org/issue6081


Is there a way to use python string.format such that no exception is thrown when an index is missing, instead an empty string is inserted.

result = "i am an {error} example string {error2}".format(hello=2,error2="success")

here,result should be :

"i am an   example string success"

Right now, python throws a keyerror and stops formatting. Is it possible to change this behavior ?

Thanks

Edit:

There exists Template.safe_substitute (even that leaves the pattern intact instead of inserting an empty string) , but couldn't something similar for string.format

The desired behavior would be similar to string substitution in php.

class Formatter(string.Formatter):
  def get_value(self,key,args,kwargs):
    try:
        if hasattr(key,"__mod__"):
            return args[key]
        else:
            return kwargs[key]
    except:
        return ""

This seems to provide the desired behavior.

解决方案

str.format() doesn't expect a mapping object. Try this:

from collections import defaultdict

d = defaultdict(str)
d['error2'] = "success"
s = "i am an {0[error]} example string {0[error2]}"
print s.format(d)

You make a defaultdict with a str() factory that returns "". Then you make one key for the defaultdict. In the format string, you access keys of the first object passed. This has the advantage of allowing you to pass other keys and values, as long as your defaultdict is the first argument to format().

Also, see http://bugs.python.org/issue6081

这篇关于Python的字符串格式压制/沉默keyerror / indexerror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆