Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to insert character

Tags:

python

string

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?

like image 930
Anycorn Avatar asked Mar 17 '26 07:03

Anycorn


2 Answers

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.

like image 185
Zeugma Avatar answered Mar 19 '26 20:03

Zeugma


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'
like image 40
garnertb Avatar answered Mar 19 '26 21:03

garnertb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!