2016-03-24 33 views
-1

我的應用str.format對於my_xpath下面有什麼問題?如何通過函數傳遞多個字符串到str.format()

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

...這是行不通的,而不是拋出一個KeyErrormy_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

你缺少return語句在功能 –

+0

好,只是認爲「漸無回」可能已經因爲 –

回答

1

字符串是不可變的,str.format創建一個新字符串並返回它,它不會修改原始字符串。你必須將格式分配給一個新的字符串並返回它。除此之外,你的第二個方式是正確的..

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

感謝您的幫助。是的,現在看起來很明顯。我看錯例子並假設它們是完整的。 – Winterflags

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}) 
+0

@JoranBeasley THX指點的out –

相關問題