[Python-ideas] Briefer string format

Mike Miller python-ideas at mgmiller.net
Mon Jul 20 01:35:01 CEST 2015


Hi,

Ok, I kept the message brief because I thought this subject had previously been 
discussed often.  I've expanded it to explain better for those that are interested.

---

Needed to whip-up some css strings, took a look at the formatting I had done
and thought it was pretty ugly.  I started with the printf style, and had
pulled out the whitespace as vars in order to have a minification option:

     csstext += '%s%s%s{%s' % (nl, key, space, nl)

Decent but not great, a bit hard on the eyes.  So I decided to try .format():

     csstext += '{nl}{key}{space}{{{nl}'.format(**locals())

This looks a bit better if you ignore the right half, but it is longer and not
as simple as one might hope.  It is much longer still if you type out the
variables needed as kewword params!  The '{}' option is not much improvement
either.

    csstext += '{nl}{key}{space}{{{nl}'.format(nl=nl, key=key, ...  # uggh
    csstext += '{}{}{}{{{}'.format(nl, key, space, nl)

I've long wished python could format strings easily like bash or perl do, ...
and then it hit me:

     csstext += f'{nl}{key}{space}{{{nl}'

An "f-formatted" string could automatically format with the locals dict. Not
yet sure about globals, and unicode only suggested for now.  Perhaps could be
done directly to avoid the .format() function call, which adds some overhead
and tends to double the length of the line?

I remember a GvR talk a few years ago giving a 'meh' on .format() and have
agreed, using it only when I have a very large or complicated string-building
need, at the point where it begins to overlap Jinja territory.  Perhaps this is
one way to make it more comfortable for everyday usage.

I've seen others make similar suggestions, but to my knowledge they didn't
include this pleasing brevity aspect.

-Mike



On 07/19/2015 04:27 PM, Eric V. Smith wrote:
> On Jul 19, 2015, at 7:12 PM, Mike Miller <python-ideas at mgmiller.net> wrote:
>>
>> Have long wished python could format strings easily like bash or perl do, ...
>> and then it hit me:
>>
>>     csstext += f'{nl}{selector}{space}{{{nl}'
>>
>> (This script included whitespace vars to provide a minification option.)
>>
>> I've seen others make similar suggestions, but to my knowledge they didn't
>> include this pleasing brevity aspect.
>
> What would this do? It's not clear from your description.
>
> Eric.
>
>


More information about the Python-ideas mailing list