String formatting named parameters?

前端 未结 7 1095
长发绾君心
长发绾君心 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:29

    Solution in Python 3.6+

    Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:

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

    This will evaluate my_url, so if it's not defined you will get a NameError. In fact, instead of my_url, you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s, just like with regular, pre-literal string formatting.

    For details on literal string formatting, see PEP 498, where it was first introduced.

    0 讨论(0)
提交回复
热议问题