字符串格式化命名参数?

问题:字符串格式化命名参数?

我知道这是一个非常简单的问题,但我不知道该如何使用Google。

我能怎么做

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

所以要my_url使用两次?我假设我必须“命名” the %s,然后在参数中使用字典,但是我不确定正确的语法吗?


仅供参考,我知道我可以my_url在参数中使用两次,但这不是重点:)

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

how can I do

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

So that my_url is used twice? I assume I have to “name” the %s and then use a dict in the params, but I’m not sure of the proper syntax?


just FYI, I’m aware I can just use my_url twice in the params, but that’s not the point :)


回答 0

在Python 2.6+和Python 3中,您可能选择使用更新的字符串格式化方法。

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

这样可以避免重复输入参数,或者

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

如果要命名参数。

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

这是严格的位置,只有警告:format()参数遵循Python规则,其中必须首先使用未命名的args,然后是命名参数,然后是* args(类似于list或tuple的序列),然后是* kwargs(一种dict如果您知道什么对您有好处,请使用字符串进行键控)。首先通过将命名值替换为它们的标签来确定插值点,然后从剩下的位置进行定位。因此,您也可以这样做…

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

但这不是…

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

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))

回答 1

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

回答 2

Python 3.6+中的解决方案

Python 3.6引入了文字字符串格式化,因此您可以格式化命名参数,而无需在字符串外重复任何命名参数:

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

这将进行评估my_url,因此,如果未定义,您将获得NameError。实际上,my_url您可以编写一个任意的Python表达式(而不是),只要它的计算结果为字符串(由于:s格式代码)即可。如果要为表达式的结果表示字符串表示形式(可能不是字符串),请替换:s!s,就像一般,预文字字符串格式化。

有关文字字符串格式的详细信息,请参阅PEP 498(首次引入该格式)。

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.


回答 3

您将沉迷于语法。

同样是C#6.0,EcmaScript开发人员也熟悉此语法。

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

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

回答 4

对于构建HTML页面,您要使用模板引擎,而不是简单的字符串插值。

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


回答 5

与字典方式一样,了解以下格式可能会很有用:

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

这是一点点的冗余,并且在修改代码时,字典方式当然不易出错,但是仍然可以使用元组进行多次插入。第%s一个元素替换了元组中的第一个元素,第二%s个元素替换了元组中的第二个元素,以此类推。

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.