Thursday, March 26, 2009

Python: Reversing a string, Replacing text in reverse

This blog is going to be filled with a lot of quick little hints, mostly for myself but others might find them useful too.

Strings in python don't have a built in (simple) way to reverse them, this is how its done:

'1234'[::-1]


And here are 2 functions, one so you don't have to remember how to reverse a string, and another to help with replacing in reverse.



def rev(s):
return str(s)[::-1]
#end def

def replacerev(s,old,new,count=-1):
"use count=1 to replace the last match of old with new in s, count = 2 for 2 replaces, and so on"
return rev( rev(str(s)).replace(rev(old),rev(new),int(count)) )
#end def

rev('1234')
replacerev('FOO BAR FOO','FOO','QUUX',1)
replacerev('FOO BAR FOO','FOO','QUUX',2)


No comments: