Reputation: 51465
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?
Upvotes: 2
Views: 172
Reputation: 9584
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'
Upvotes: 4
Reputation: 32095
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.
Upvotes: 4
Reputation: 133544
>>> import re
>>> re.sub(r'( !|$)', r' &\1', 'foo bar', 1)
'foo bar &'
>>> re.sub(r'( !|$)', r' &\1', 'foo ! bar', 1)
'foo & ! bar'
Upvotes: 2
Reputation: 214949
s1 = "foo bar"
s2 = "foo ! bar"
import re
print re.sub(r'^([^!]+)( |$)', r'\1 &\2', s1) # foo bar &
print re.sub(r'^([^!]+)( |$)', r'\1 &\2', s2) # foo & ! bar
Upvotes: 1
Reputation: 14251
Doing multiple sentences in one line:
>>> s = ["foo bar", "foo ! bar"]
>>> [x + ' &' if not '!' in x else x.replace('!','& !', 1) for x in s]
['foo bar &', 'foo & ! bar']
Upvotes: 1