我有一个要格式化的字符串,但是我用来格式化的值可能是正确的值(None
或''
),也可能不是。无论如何,如果传递了这些不正确的值之一,我仍然希望字符串格式化,但忽略任何无效的值。例如:
mystring = "{:02d}:{:02d}"
mystring.format('', 1)
在这种情况下,我希望输出为:01
,从而否定了''
不适用于字符串中第一个值的事实。我看着像
class Default(dict):
def __missing__(self, key):
return key.join("{}")
d = Default({"foo": "name"})
print("My {foo} is {bar}".format_map(d)) # "My name is {bar}"
但是由于我没有使用字典来存储值,因此我认为该解决方案不会对我有用。
您可以编写自己的格式化程序并重写format_field()
以捕获这些错误,并仅返回空字符串。这是基础知识(您可能需要编辑以仅捕获某些错误):
import string
class myFormat(string.Formatter):
def format_field(self, value, format_spec):
try:
return super().format_field(value, format_spec)
except ValueError:
return ''
fmt = myFormat()
mystring = "{:02d}:{:02d}"
print(fmt.format(mystring, *(2, 1)))
# 02:01
print(fmt.format(mystring, *('', 1)))
# :01
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句