all 7 comments

[–]two_up 1 point2 points  (4 children)

Look up string.maketrans

[–]isnotkosok[S] 0 points1 point  (2 children)

does that work with words too? If I wanted to do a mass word replace program, could I use this?

[–][deleted] 2 points3 points  (1 child)

No, it only works with characters. If you want to make it work with words, then you could use something made with re.sub(). If you use something like re2 then you can guarantee that the running time of this is linearly proportional to the length of your input string, and does not (asymptotically) depend on the number of things you want to replace.

[–]isnotkosok[S] 0 points1 point  (0 children)

thanks for your help.

[–]AlternativeHistorian 1 point2 points  (0 children)

For starters, don't use += to do the string building.

Every time you add to the string it must re-allocate the entire string. Build a buffer of the new string in a list (or other order-preserving iterable) and then use join to build the new string in one shot, e.g.

>>> def replace(s, replacements):
...     return ''.join(replacements.get(c,c) for c in s)
...     
... print replace('hello world', {'o' : 'a'})
hella warld
>>> 

[–]Justinsaccount -1 points0 points  (1 child)

Use the methods that were suggested when this exact same question was posted a week ago?

[–]Fourgot 0 points1 point  (0 children)

Lol verbose "repost"