我对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")
答案 0 :(得分:1)
根据文档,我们应该传递基于键值的参数或字典:
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)