Title: format() to lower and uppercase
Type: enhancement Stage: resolved
Components: Interpreter Core Versions: Python 2.7
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: Hervé Cauwelier, eric.smith, r.david.murray
Priority: normal Keywords:

Created on 2010-12-09 15:33 by Hervé Cauwelier, last changed 2010-12-10 08:37 by Hervé Cauwelier. 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)
>>> '{0:X}'.format(123)

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:]
            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.
Date User Action Args
2010-12-10 08:37:15Hervé Cauweliersetmessages: + msg123720
2010-12-09 16:53:52eric.smithsetnosy: + eric.smith
messages: + msg123686
2010-12-09 15:53:25r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg123685

resolution: rejected
stage: resolved
2010-12-09 15:33:41Hervé Cauweliercreate