質問

In Python, I'm trying to implement a pseudo-ternary operator within a template string. A value is inserted into a string if kwargs has a specific key.

re module has a way do exactly what I need in re.sub(), you can pass a function to be called on matches. What I can't do is to pass **kwargs to it. Code follows

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: is the problem of course, as process_pseudo_ternary's kwargs are empty.

Any ideas on how to pass these? m.sub(function, string) doesn't take arguments.

The final string is to be: some text val_if_true some text (because the dictionary has the key named 'pseudo_test').

Feel free to redirect me to a different implementation of ternary operator in a string. I'm aware of Python conditional string formatting . I need the ternary to be in the string, not in the string's formatting tuple/dict.

役に立ちましたか?

解決

If i understand it correctly, you could use something like http://docs.python.org/library/functools.html#functools.partial

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

EDIT: Changed a little, to match your code better.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top