A hack to quickly replace multiple characters/strings in a string with characters from another string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # mrepalce.py - quick string replacement
import string
import array
def mreplace(s, chararray, newchararray):
""" Replace occurences of chars in
chararray in string 's' with elements in
newchararray """
slist=list(s)
dlist=list(chararray)
rlist=list(newchararray)
for x in range(0, len(slist)):
charitem=slist[x]
if charitem in dlist:
index=dlist.index(charitem)
try:
slist[x]=rlist[index]
except ValueError:
pass
return array.array('c', slist).tostring()
|
Quick and nifty hack. It is better than many string.replace() cycles.
Tags: text
hew. How is that better than multiple string.replaces? I tried it against this:
And it was a lot slower :P
Something that is included AND better. There's this magical little thing call string.translate that does EXACTLY what both of you want.
Running this on 512k of random data, translating all 256 characters (chr(0) becomes chr(255), chr(1) becomes chr(254), etc.), the times to execute on my PII-400 are:
mreplace: 39.2030000687
mreplace2: 8.39099991322
mreplace3: 0.0149999856949
I believe translate is a C function call. Could be why it beats the other two by factors of almost 3000 and 600 respectively.
Not the same. There are differences in these algorithms. The maketrans() function requires that the characters mapped are the same length. The replace() function has no such requirement.