Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 226345
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T19:30:09+00:00 2026-05-11T19:30:09+00:00

In PHP, you have preg_replace($patterns, $replacements, $string) , where you can make all your

  • 0

In PHP, you have preg_replace($patterns, $replacements, $string), where you can make all your substitutions at once by passing in an array of patterns and replacements.

What is the equivalent in Python?

I noticed that the string and re functions replace() and sub() don’t take dictionaries…

Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as '\d+S', and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T19:30:09+00:00Added an answer on May 11, 2026 at 7:30 pm

    closest is probably:

    somere.sub(lambda m: replacements[m.group()], text)
    

    for example:

    >>> za = re.compile('z\w')
    >>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')
    'fa BLU BLA bu'
    

    with a .get instead of []-indexing if you want to supply a default for matches that are missing in replacements.

    Edit: what rick really wants is to have a dict with keys to be taken as regular expression patterns, such as '\d+S', and (hopefully) constant string values (hopefully w/o backreferences). The cookbook recipe can be adapted for this purpose:

    def dict_sub(d, text): 
      """ Replace in 'text' non-overlapping occurences of REs whose patterns are keys
      in dictionary 'd' by corresponding values (which must be constant strings: may
      have named backreferences but not numeric ones). The keys must not contain
      anonymous matching-groups.
      Returns the new string.""" 
    
      # Create a regular expression  from the dictionary keys
      regex = re.compile("|".join("(%s)" % k for k in d))
      # Facilitate lookup from group number to value
      lookup = dict((i+1, v) for i, v in enumerate(d.itervalues()))
    
      # For each match, find which group matched and expand its value
      return regex.sub(lambda mo: mo.expand(lookup[mo.lastindex]), text)
    

    Example use:

      d={'\d+S': 'wot', '\d+T': 'zap'}
      t='And 23S, and 45T, and 66T but always 029S!'
      print dict_sub(d, t)
    

    emits:

    And wot, and zap, and zap but always wot!
    

    You could avoid building lookup and just use mo.expand(d.values()[mo.lastindex-1]), but that might be a tad slow if d is very large and there are many matches (sorry, haven’t precisely measured/benchmarked both approaches, so this is just a guess;-).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the PHP preg_replace in C#? I have an array of string that
Most of my PHP apps have an ob_start at the beginning, runs through all
I can't quite figure out the right pattern to use with PHP's preg_replace function.
Does PHP have a method of having auto-generated class variables? I think I've seen
I have PHP configured so that magic quotes are on and register globals are
We have PHP 5.2.6 deployed to c:\php and in that folder there is the
In php I have open a .php file and want to evaluate certain lines.
For PHP I have a date I want line wrapped. I have $date =
If I have $var defined in Page1.php and in Page2.php I have //Page2.php include('Page1.php');
Why do PHP regexes have the surrounding delimiters? It seems like it would be

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.