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 …