darkoucha
darkoucha

Reputation: 31

is there a way to convert the ?: operator in a string to python conditional statment?

I am using python to parse a text file which contains the ternary operator a ? b:c

I would like to convert the ?: operator to python conditional statement b if a else c.

example:

expression = "(2.4**l2) + 8.0*( (l3>=l4) ? k2:k3 )"
converted_expression = "(2.4**l2) + 8.0*(k2 if (l3>=l4) else k3 )"

Upvotes: 0

Views: 119

Answers (2)

DeepSpace
DeepSpace

Reputation: 81654

How about using a regex? This particular regex doesn't care about spaces and is using named capture groups for clarity

import re

regex = re.compile(r'\((?P<cond>.*)\) ?\? ?(?P<if_true>.+):(?P<if_false>.+)')

string = '(l3>=l4) ? k2:k3'
match = regex.search(string)
print('{if_true} if {cond} else {if_false}'.format(if_true=match.group('if_true'),
                                                   cond=match.group('cond'),
                                                   if_false=match.group('if_false')))

# k2 if l3>=l4 else k3

Upvotes: 3

Organis
Organis

Reputation: 7316

Well, this is probably kind of limited, but you can go with the following:

converted_expression = "(2.4**l2) + 8.0*([k3,k2][bool(l3>=l4)])"

The bool(...) part will return False or True which is auto-converted into 0 and 1 respectively as a list index.

Upvotes: -1

Related Questions