The Python Oracle

String formatting named parameters?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Question
00:46 Accepted answer (Score 46)
01:49 Answer 2 (Score 232)
01:59 Answer 3 (Score 102)
03:08 Answer 4 (Score 7)
03:33 Thank you

--

Full question
https://stackoverflow.com/questions/2451...

Accepted answer links:
[PEP 498]: https://www.python.org/dev/peps/pep-0498/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #syntax

#avk47



ANSWER 1

Score 236


print '<a href="%(url)s">%(url)s</a>' % {'url': my_url}



ANSWER 2

Score 105


In Python 2.6+ and Python 3, you might choose to use the newer string formatting method.

print('<a href="{0}">{0}</a>'.format(my_url))

which saves you from repeating the argument, or

print('<a href="{url}">{url}</a>'.format(url=my_url))

if you want named parameters.

print('<a href="{}">{}</a>'.format(my_url, my_url))

which is strictly positional, and only comes with the caveat that format() arguments follow Python rules where unnamed args must come first, followed by named arguments, followed by *args (a sequence like list or tuple) and then *kwargs (a dict keyed with strings if you know what's good for you). The interpolation points are determined first by substituting the named values at their labels, and then positional from what's left. So, you can also do this...

print('<a href="{not_my_url}">{}</a>'.format(my_url, my_url, not_my_url=her_url))

But not this...

print('<a href="{not_my_url}">{}</a>'.format(my_url, not_my_url=her_url, my_url))



ANSWER 3

Score 7


You will be addicted to syntax.

Also C# 6.0, EcmaScript developers has also familier this syntax.

In [1]: print '{firstname} {lastname}'.format(firstname='Mehmet', lastname='Ağa')
Mehmet Ağa

In [2]: print '{firstname} {lastname}'.format(**dict(firstname='Mehmet', lastname='Ağa'))
Mehmet Ağa



ANSWER 4

Score 5


For building HTML pages, you want to use a templating engine, not simple string interpolation.