String formatting (%)
Peter Hansen
peter at engcorp.com
Thu Apr 29 09:02:31 EDT 2004
Daniel 'Dang' Griffith wrote:
> On Wed, 28 Apr 2004 09:15:02 -0400, Peter Hansen <peter at engcorp.com>
> wrote:
>>I suspect there's also a regular expression that could deal with
>>that, but I don't want to know what it is. ;-)
>
> Since you don't want to know what it is, I'll at least tell you
> where it is: In Mastering Regular Expressions by Jeffrey E. F. Friedl.
> I don't have it front of me, but it's the "commafying" example. A
> quick search of the author's site looks like it's on pgs 64-65.
Thank you. You can even get the code listings online, which is
very nice since my copy has migrated into a closet during a recent
move.
>>> import re
>>> s = '21421906.12'
>>>
>>> re.sub(r'(?<=\d)(?=(\d\d\d)+\.)', ',', s)
'21,421,906.12'
> Of course, the OP would substitute spaces for the commas.
>>> _.replace(',', ' ')
'21 421 906.12'
Very nice... quite elegant, I suppose. I struggled with it a
bit myself yesterday but I'm no RE expert. :-(
-Peter
More information about the Python-list
mailing list