Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Python function that does multiple string replace ops in a single pass.
import re
def replace(string, substitutions):
substrings = sorted(substitutions, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
return regex.sub(lambda match: substitutions[match.group(0)], string)
@carlsmith

This comment has been minimized.

Copy link
Owner Author

carlsmith commented Apr 5, 2017

If you ran the following code, output would be "spam FOO BAR FOO BAR spam".

string = "spam foo bar foo bar spam"
substitutions = {"foo": "FOO", "bar": "BAR"}
output = replace(string, substitutions)
@ashishsurve21

This comment has been minimized.

Copy link

ashishsurve21 commented Sep 12, 2018

Thanks! Nice Solution!!!!

@thirumalailucifer

This comment has been minimized.

Copy link

thirumalailucifer commented Dec 26, 2018

One of the best Method hats off to you !

@feldi-to-go

This comment has been minimized.

Copy link

feldi-to-go commented May 17, 2019

Hi all!
I am a newly in programming Python, and found your code regarding easy replacing text, using Python.
Now I am facing a problem to use your code, where the substitutions are not pure text like "foo": "Foo", rather using regex to find special pattern.
For example: I have a string with a double tab's, double blank's, certain numbers or text, and those need to replace each of them different. The double tab with a single tab, the double blank with a single blank, all "006" with "007" and so on.
Is it possible, and how is it possible to modify you code to have a dictionary (or list) with regex-pattern and on the other hand, the related replacements?
I would appreciate to get some help on this topic.
Thank you in advance!

@ridhitatineni1

This comment has been minimized.

Copy link

ridhitatineni1 commented Nov 26, 2019

This is such a cool solution! Thank you @carlsmith !

@ClamCao

This comment has been minimized.

Copy link

ClamCao commented Dec 2, 2019

sorted(substitutions, key=len, reverse=True)

cannot understand whta it's meaning?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.