小编mfu*_*man的帖子

How to provide custom formatting from format string?

I can use a custom class to extend Python's string formatting:

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)
Run Code Online (Sandbox Code Playgroud)

I can then use this class to format arguments which are passed to a strings format method:

unformatted_string = 'uppercase: {s:u}, lowercase: {s:l}'
print unformatted_string.format(s=CaseStr('abc'))
Run Code Online (Sandbox Code Playgroud)

While this works it seems awkward that the custom format specifier is in the base string, but …

python string format

5
推荐指数
1
解决办法
59
查看次数

标签 统计

format ×1

python ×1

string ×1