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 th开发者_JS百科at 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
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.
精彩评论