gpt4 book ai didi

python - 将 kwargs 传递给 re.sub()

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:38 26 4
gpt4 key购买 nike

在Python中,我试图在模板字符串中实现伪三元运算符。如果 kwargs 具有特定键,则将值插入到字符串中。

re 模块有一种方法可以完全满足我在 re.sub() 中的需要,您可以传递一个在匹配时调用的函数。我不能做的就是将 **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})

line 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 。我需要三元位于字符串中,而不是字符串的格式元组/字典中。

最佳答案

如果我理解正确的话,你可以使用类似http://docs.python.org/library/functools.html#functools.partial的东西

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

编辑:做了一点更改,以更好地匹配您的代码。

关于python - 将 kwargs 传递给 re.sub(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com