我可以使用自定义类来扩展 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'))
虽然这种方法有效,但自定义格式说明符位于基本字符串中似乎很尴尬,但传递给其格式方法的参数实际上负责解析格式说明符。
有没有办法将解释自定义字符串所需的知识放在基本字符串本身中?
class CaseStrWrapper(str):
...
unformatted_string = CaseStrWrapper('uppercase: {s:u}, lowercase: {s:l}')
print unformatted_string.format(s='abc')
你通常会使用自定义字符串格式 https://docs.python.org/2/library/string.html#custom-string-formatting为此(参见PEP 3101 https://www.python.org/dev/peps/pep-3101/)。对于你的情况,你可以有这样的东西:
import string
class MyFormatter(string.Formatter):
def format_field(self, value, format_spec):
if isinstance(value, str):
if format_spec.endswith('u'):
value = value.upper()
format_spec = format_spec[:-1]
elif format_spec.endswith('l'):
value = value.lower()
format_spec = format_spec[:-1]
return super(MyFormatter, self).format(value, format_spec)
fmt = MyFormatter()
print(fmt.format('uppercase: {s:u}, lowercase: {s:l}', s='abc'))
# uppercase: ABC, lowercase: abc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)