Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从格式字符串提供自定义格式?_Python_String_Format - Fatal编程技术网

Python 如何从格式字符串提供自定义格式?

Python 如何从格式字符串提供自定义格式?,python,string,format,Python,String,Format,我可以使用自定义类扩展Python的字符串格式: class CaseStr(str): def __format__(self, fmt): if fmt.endswith('u'): s = self.upper() fmt = fmt[:-1] elif fmt.endswith('l'): s = self.lower() fmt = fmt[:-1]

我可以使用自定义类扩展Python的字符串格式:

class CaseStr(str):
    def __format__(self, fmt):
        if fmt.endswith('u'):
            s = self.upper()
            fmt = fmt[:-1]
        elif fmt.endswith('l'):
            s = self.lower()
            fmt = fmt[:-1]
        else:
            s = str(self)
        return s.__format__(fmt)
然后,我可以使用此类格式化传递给字符串格式方法的参数:

unformatted_string = 'uppercase: {s:u}, lowercase: {s:l}'
print unformatted_string.format(s=CaseStr('abc'))
虽然这样做看起来很尴尬,因为自定义格式说明符位于基字符串中,但是传递给它的format方法的参数实际上负责解析格式说明符

有没有办法将解释自定义字符串所需的知识放在基本字符串本身中

class CaseStrWrapper(str):
    ...

unformatted_string = CaseStrWrapper('uppercase: {s:u}, lowercase: {s:l}')
print unformatted_string.format(s='abc')
您通常会使用(请参阅)。对于您的情况,您可以有如下内容:

导入字符串
类MyFormatter(string.Formatter):
定义格式字段(自身、值、格式规格):
如果isinstance(值,str):
如果格式_spec.endswith('u'):
value=value.upper()
格式规格=格式规格[:-1]
elif格式_spec.endswith('l'):
value=value.lower()
格式规格=格式规格[:-1]
返回super(MyFormatter,self).format(值,格式\规格)
fmt=MyFormatter()
打印(fmt.format('大写:{s:u},小写:{s:l}',s='abc'))
#大写:ABC,小写:ABC

您可以重载格式,但格式说明符理解是要格式化的东西的工作,而不是
str
的工作。这很像每种类型都有自己的
\uuu str\uuu
方法,而不是试图让
str
类知道如何对每种类型的对象进行字符串化。为什么不使用格式字符串呢?e、 g.
f“{s.upper()}{s.lower()}”
?这听起来像是一个格式化工具,而不是
str.format
,它更适合您想要做的事情。@SamMason我使用的是Python 2.7。