I have two transform cases:
s = "foo bar" #-> "foo bar &"
s = "foo ! bar" # -> "foo & ! bar" -> notice not '&!'
I did it like this:
t = s.split("!", 1)
t[0] = t[0] + " &"
" !".join(t)
What's a more pythonic way to do the same?
str.partition is built for the purpose of operator parsing:
p = s.partition(' !')
print p[0]+' &'+p[1]+p[2]
It is adapted to prefix and infix operator when parsing from left to right. The fact it always returns a 3-tuple allows to use it even when your operator is not found and apply an action on your result as shown above.
Not sure if this is any more pythonic, but the example above can be done as a one-liner.
>>> s = "foo ! bar"
>>> s = s.replace(' ! ', ' & ! ') if '!' in s else s + ' &'
>>> s
'foo & ! bar'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With