Issue 10660: format() to lower and uppercase (original) (raw)

Created on 2010-12-09 15:33 by Hervé Cauwelier, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg123684 - (view) Author: Hervé Cauwelier (Hervé Cauwelier) Date: 2010-12-09 15:33
Hexadecimals can be formatted to lower and uppercase: >>> '{0:x}'.format(123) '7b' >>> '{0:X}'.format(123) '7B' I would like the same thing for strings: >>> '{0.lastname:u} {0.firstname}'.format(user) 'DOE John' I first thought using "S" for uppercase, but "s" is not available for lowercase. So I thought about "u" and "l". The alternative is to write: >>> '{0} {1}'.format(user.lastname.upper(), user.firstname) 'DOE John' But I find it less compact and elegant.
msg123685 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2010-12-09 15:53
The format support is written specifically so that it is extensible. You can write your own string subclass that extends the formatting mini-language with whatever features you find useful. There are too many variations on what might be useful with regards to case transformations for this to be a sensible addition to the language itself. Much better that an application create use-case tailored facilities. (Note, by the way, that new features can only go in to 3.3 at this point.)
msg123686 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2010-12-09 16:53
I agree with David. Here's an example of using such a subclass. It extends the format string for strings to begin with an optional 'u' or 'l': ----------------------- class U(str): def __format__(self, fmt): if fmt[0] == 'u': s = self.upper() fmt = fmt[1:] elif fmt[0] == 'l': s = self.lower() fmt = fmt[1:] else: s = str(self) return s.__format__(fmt) name = 'Hervé Cauwelier' print('{0:u*^20} {0:l*^20} {0:*^20}'.format(U(name))) ----------------------- It produces: **HERVÉ CAUWELIER*** **hervé cauwelier*** **Hervé Cauwelier***
msg123720 - (view) Author: Hervé Cauwelier (Hervé Cauwelier) Date: 2010-12-10 08:37
Thanks for the example. The Python 2.7 documentation about the mini-language doesn't clearly state that it is extensible and how. we see examples of formatting but not of extending. Your example would be welcome in the documentation.
History
Date User Action Args
2022-04-11 14:57:10 admin set github: 54869
2010-12-10 08:37:15 Hervé Cauwelier set messages: +
2010-12-09 16:53:52 eric.smith set nosy: + eric.smithmessages: +
2010-12-09 15:53:25 r.david.murray set status: open -> closednosy: + r.david.murraymessages: + resolution: rejectedstage: resolved
2010-12-09 15:33:41 Hervé Cauwelier create