String formatting named parameters?

前端 未结 7 1094
长发绾君心
长发绾君心 2020-12-07 13:44

I know it\'s a really simple question, but I have no idea how to google it.

how can I do

print \'%s\' % (my_url)


        
相关标签:
7条回答
  • 2020-12-07 14:02

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

    0 讨论(0)
  • 2020-12-07 14:03

    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))
    
    0 讨论(0)
  • 2020-12-07 14:17

    Another option is to use format_map:

    print('<a href="{s}">{s}</a>'.format_map({'s': 'my_url'}))
    
    0 讨论(0)
  • 2020-12-07 14:19

    As well as the dictionary way, it may be useful to know the following format:

    print '<a href="%s">%s</a>' % (my_url, my_url)

    Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.

    0 讨论(0)
  • 2020-12-07 14:24
    print '<a href="%(url)s">%(url)s</a>' % {'url': my_url}
    
    0 讨论(0)
  • 2020-12-07 14:25

    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
    
    0 讨论(0)
提交回复
热议问题