nlper
nlper

Reputation: 529

transforming the same character into different characters depending on position in word

I thank coffee-grinder very much for asking a question for me a few hours ago. Now that I am a member, I'd like to rephrase the question a bit.

What is the best way to state that a word-initial 's' transforms into a '$' and the remainder of the 's' transforms into a '5' using regular expressions and python?

I attempted to do this in the following code, but the outcome is wrong. The general rule for 's' conversion is greedy and does not give the word-initial 's' rule to come into play. I would appreciate any help with this. Thanks.

text = 'sassy'

for (regexp,subst) in [ (r's', '5'),(r'^s', '$') ]:

  text = re.sub(regexp,subst,text)

...

text

5A55y

Upvotes: 1

Views: 88

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

You're just not being specific enough. You need a non-zero lookbehind assertion on the first one.

>>> text = 'sassy'
>>> for (regexp,subst) in [ (r'(?<=.)s', '5'),(r'^s', '$') ]:
...   text = re.sub(regexp,subst,text)
... 
>>> text
'$a55y'

That, or change the order.

All bets are out when one of your substitutions feeds into another match though.

Upvotes: 2

Related Questions