字符串格式化命名参数? [英] String formatting named parameters?

查看:45
本文介绍了字符串格式化命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常简单的问题,但我不知道如何用谷歌搜索它.

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

我该怎么办

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

所以 my_url 被使用了两次?我假设我必须命名"%s,然后在参数中使用字典,但我不确定正确的语法?

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?

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

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

推荐答案

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

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

如果你想要命名参数.

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

这是严格的位置,并且只需要注意 format() 参数遵循 Python 规则,其中未命名的 args 必须首先出现,然后是命名的参数,然后是 *args(像列表或元组这样的序列),然后是 *kwargs(如果你知道什么对你有好处的话,一个以字符串为键的字典).插值点首先通过替换其标签上的命名值来确定,然后根据剩下的位置进行定位.所以,你也可以这样做...

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

但不是这个...

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

这篇关于字符串格式化命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆