2012-10-07 54 views
1

在Python中,我試圖在模板字符串中實現僞三元運算符。如果kwargs具有特定的鍵,則將值插入到字符串中。將kwargs傳遞給re.sub()

re模塊有辦法完成我在re.sub()所需要的,你可以傳遞一個函數在match上被調用。我不能做的是通過**kwargs。代碼如下

import re 

template_string = "some text (pseudo_test?val_if_true:val_if_false) some text" 

def process_pseudo_ternary(match, **kwargs): 
    if match.groups()[0] in kwargs: 
     return match.groups()[1] 
    else: 
     return match.groups()[2] 

def process_template(ts, **kwargs): 
    m = re.compile('\((.*)\?(.*):(.*)\)') 
    return m.sub(process_pseudo_ternary, ts) 

print process_template(template_string, **{'pseudo_test':'yes-whatever', 'other_value':42}) 

if match.groups()[0] in kwargs:當然是問題,因爲process_pseudo_ternary的kwargs是空的。

關於如何通過這些的任何想法? m.sub(function, string)不帶參數。

最後一個字符串應爲:some text val_if_true some text(因爲字典有一個名爲'pseudo_test'的鍵)。

隨意將我重定向到字符串中三元運算符的不同實現。我知道Python conditional string formatting。我需要三元組在字符串中,而不是在字符串的格式化元組/字典中。

回答

1

如果我理解正確的話,你可以使用類似http://docs.python.org/library/functools.html#functools.partial

return m.sub(partial(process_pseudo_ternary, custom_1=True, custom_2=True), ts) 

編輯:變化不大,以滿足你的代碼更好。

+0

正確!但是,它將會等待一天,其他(如果有的話)答案是公平的,但是,謝謝 – bartekbrak