用指定变量替换 python 字符串的部分
Replacing section of python string with a designated variable
目前我正在处理一条消息,我想包含多个变化的变量。现在我不确定我是否解释正确,因此这里有一个例子:
"""
Hello world!
%s
%(what goes here?)
""".format()
基本上我想再应用一个“%s”,虽然我不知道该怎么做。
对不起,如果这很简单;关于与上述问题相关的方法,我找不到太多信息。
非常感谢您的帮助,谢谢!
编辑:
REPLY_MENTION_TEMPLATE = """
Example message:
%s
{pm_link}.
{info_post}.
|{source_link}|
""".format(pm_link = pm_link, info_post = info_post, source_link = source_link)
exampleMess = (REPLY_MENTION_TEMPLATE % eampleVar)
(所以基本上,我想添加另一个“%”以便我可以输入另一个变量)
您可以将多个 key/value 对传递给 Python 的 str.format()
format(format_string, *args, **kwargs)
format() is the primary API
method. It takes a format string and an arbitrary set of positional
and keyword arguments. format() is just a wrapper that calls
vformat().
示例:
>>> print "Hello {foo:s} and {bar:s}".format(foo="World", bar="Foobar!")
Hello World and Foobar!
不过,可能建议您使用 String Templates here or an alternative templating engine such as Jinja2
基本 Jinja2 示例:
from jinja2 import Environment
HTML = """
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
Hello.
</body>
</html>
"""
def print_html_doc():
print Environment().from_string(HTML).render(title='Hellow Gist from GutHub')
您可以轻松安装Jinja2 pip
:
pip install jinja2
目前我正在处理一条消息,我想包含多个变化的变量。现在我不确定我是否解释正确,因此这里有一个例子:
"""
Hello world!
%s
%(what goes here?)
""".format()
基本上我想再应用一个“%s”,虽然我不知道该怎么做。
对不起,如果这很简单;关于与上述问题相关的方法,我找不到太多信息。
非常感谢您的帮助,谢谢!
编辑:
REPLY_MENTION_TEMPLATE = """
Example message:
%s
{pm_link}.
{info_post}.
|{source_link}|
""".format(pm_link = pm_link, info_post = info_post, source_link = source_link)
exampleMess = (REPLY_MENTION_TEMPLATE % eampleVar)
(所以基本上,我想添加另一个“%”以便我可以输入另一个变量)
您可以将多个 key/value 对传递给 Python 的 str.format()
format(format_string, *args, **kwargs)
format() is the primary API method. It takes a format string and an arbitrary set of positional and keyword arguments. format() is just a wrapper that calls vformat().
示例:
>>> print "Hello {foo:s} and {bar:s}".format(foo="World", bar="Foobar!")
Hello World and Foobar!
不过,可能建议您使用 String Templates here or an alternative templating engine such as Jinja2
基本 Jinja2 示例:
from jinja2 import Environment
HTML = """
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
Hello.
</body>
</html>
"""
def print_html_doc():
print Environment().from_string(HTML).render(title='Hellow Gist from GutHub')
您可以轻松安装Jinja2 pip
:
pip install jinja2