Python 我可以定义自己的格式规范吗?

Python 我可以定义自己的格式规范吗?,python,python-2.7,format,Python,Python 2.7,Format,我想定义我自己的规范,例如 def earmuffs(x): return "*"+str(x)+"*" 要使用,例如,如下所示: def triple2str(triple, fmt="g"): return "[{first:{fmt}} & {second:+{fmt}} | {third}]".format( first=triple[0], second=triple[1], third=triple[2], fmt=fmt) >>

我想定义我自己的规范,例如

def earmuffs(x):
    return "*"+str(x)+"*"
要使用,例如,如下所示:

def triple2str(triple, fmt="g"):
    return "[{first:{fmt}} & {second:+{fmt}} | {third}]".format(
        first=triple[0], second=triple[1], third=triple[2], fmt=fmt)
>>> triple2str((1,-2,3))
'[1 & -2 | 3]'
>>> triple2str((10000,200000,"z"),fmt="{:,d}".format)
'[10,000 & 200,000 | z]' # no `+` before `2`!
>>> triple2str((10000,200000,"z"),fmt=earmuffs)
'[*10000* & *200000* | z]'
以便:

## this works:
>>> triple2str((1,-2,3))
'[1 & -2 | 3]'
>>> triple2str((10000,200000,"z"),fmt=",d")
'[10,000 & +200,000 | z]'

## this does NOT work (I get `ValueError: Invalid conversion specification`)
>>> triple2str(("a","b","z"),fmt=earmuffs)
'[*a* & *b* | z]'
到目前为止,我能想到的最好的办法是

def triple2str(triple, fmt=str):
    return "[{first} & {second} | {third}]".format(
        first=fmt(triple[0]), second=fmt(triple[1]), third=triple[2])
其工作原理如下:

def triple2str(triple, fmt="g"):
    return "[{first:{fmt}} & {second:+{fmt}} | {third}]".format(
        first=triple[0], second=triple[1], third=triple[2], fmt=fmt)
>>> triple2str((1,-2,3))
'[1 & -2 | 3]'
>>> triple2str((10000,200000,"z"),fmt="{:,d}".format)
'[10,000 & 200,000 | z]' # no `+` before `2`!
>>> triple2str((10000,200000,"z"),fmt=earmuffs)
'[*10000* & *200000* | z]'
这真的是我能做的最好的了吗? 我不高兴的是,不清楚如何合并修饰符(例如上面的
+


str.format
可扩展吗?

str.format
本身不可扩展。但是,有两种方法:


一,

使用自定义字符串格式化程序:

重写
format\u字段(obj,format\u spec)
方法以捕获可调用的格式规范。然后直接调用格式化程序

此代码段可以帮助您(它至少适用于py 3.5和2.7):


二,

定义每个对象的格式方法
\uuuu format\uuuuu(self,format\u spec)
,其中
format\u spec
是在
之后的内容,例如
{var:g}
。您可以根据需要设置对象的自我呈现格式

但是,在您的例子中,对象是ints/strs,而不是自定义对象,因此此方法也没有多大帮助


作为结论:


是的,您在这个问题上的解决方案是足够的,可能是最简单的。

str.format
本身是不可扩展的。但是,有两种方法:


一,

使用自定义字符串格式化程序:

重写
format\u字段(obj,format\u spec)
方法以捕获可调用的格式规范。然后直接调用格式化程序

此代码段可以帮助您(它至少适用于py 3.5和2.7):


二,

定义每个对象的格式方法
\uuuu format\uuuuu(self,format\u spec)
,其中
format\u spec
是在
之后的内容,例如
{var:g}
。您可以根据需要设置对象的自我呈现格式

但是,在您的例子中,对象是ints/strs,而不是自定义对象,因此此方法也没有多大帮助


作为结论:


是的,您在这个问题上的解决方案已经足够了,而且可能是最简单的解决方案。

在python 3中,您可以在
f-strings
中调用函数,这可能会有所帮助

def earmuffs(val):
    return "*{}*".format(val)

form = lambda a: f"method {earmuffs(a[0])} and method {earmuffs(a[1])}"

b = ('one', 'two')

form(b)
>>>'method *one* and method *two*'

在Python3中,您可以在
f-strings
中调用函数,这可能会有所帮助

def earmuffs(val):
    return "*{}*".format(val)

form = lambda a: f"method {earmuffs(a[0])} and method {earmuffs(a[1])}"

b = ('one', 'two')

form(b)
>>>'method *one* and method *two*'

使用Python3,可以使用
f-string
调用字符串中的函数。因此
f“method{fn('a')}”
变成了
“method*a*”
,在Python3中,您可以使用
f-string
调用字符串中的函数。因此,
f“method{fn('a')}”
变成了
“method*a*”
我使用Python 2,如标记所示。