Why does this (not) work?

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 20 04:17:30 EDT 2003


Skip Montanaro <skip at pobox.com> wrote in 
news:mailman.1061329351.3443.python-list at python.org:

> If you're worried about readability of large format operations, I suggest
> you consider using dictionary expansion, e.g.:
> 
>     >>> "%(var)s - %(var)s - %(var)s" % {"var": "test"}
>     'test - test - test'
> 
> or more commonly:
> 
>     >>> var = "test"
>     >>> "%(var)s - %(var)s - %(var)s" % locals()
>     'test - test - test'
> 
I'm not sure about that last one being more common. I don't think I have 
ever had a desire to pass more variables to the string format than the ones 
I know I really want there. 

If you've upgraded to Python 2.3, then another way to write this would be:

>>> "%(var)s - %(var)s - %(var)s" % dict(var="test")

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list