如何通过函数将多个字符串传递给str.format()

时间:2016-03-24 19:44:04

标签: python string python-2.7

我对str.format申请my_xpath有什么问题?

def look_for(thing, value):
    my_xpath = "//h2[. = '{thing_placeholder}']/following::table//td[. = '{value_placeholder}']"
    my_xpath.format(thing, value)
    return my_xpath

look_for("MyThing", "MyValue")

...它不起作用,而是在KeyError应用于查找网络元素时抛出my_xpath

或者,如果我尝试使用此变体,它不会抱怨KeyError,但我会回复None

def look_for_v2(thing, value):
    my_xpath = "//h2[. = '{thing_placeholder}']/following::table//td[. = '{value_placeholder}']"
    my_xpath.format(thing_placeholder = thing, value_placeholder = value)
    return my_xpath

look_for_v2("MyThing", "MyValue")

2 个答案:

答案 0 :(得分:1)

查看str.format()

的文档

根据文档,我们应该传递基于键值的参数或字典:

str.format(*args, **kwargs)

my_xpath = "//h2[. = '{thing_placeholder}']/following::table//td[. = '{value_placeholder}']"
new_xpath = my_xpath.format({'thing_placeholder':thing, 'value_placeholder': value})

答案 1 :(得分:1)

字符串是不可变的,str.format创建一个新字符串并返回它,它不会修改原始字符串。您必须将格式分配给新字符串并返回它或其他内容。除此之外你的第二种方式是正确的..

my_new_xpath = my_xpath.format(thing_placeholder = thing, value_placeholder = value)