Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.replace equivalent (from Javascript)

I am trying to pick up python and as someone coming from Javascript I haven't really been able to understand python's regex package re

What I am trying to do is something I have done in javascript to build a very very simple templating "engine" (I understand AST is the way to go for anything more complex):

In javascript:

var rawString = 
  "{{prefix_HelloWorld}}   testing this. {{_thiswillNotMatch}} \ 
  {{prefix_Okay}}";

rawString.replace(
   /\{\{prefix_(.+?)\}\}/g,
   function(match, innerCapture){
     return "One To Rule All";
});

In Javascript that will result in:

"One To Rule All testing this. {{_thiswillNotMatch}} One To Rule All"

And the function will get called twice with:

   innerCapture === "HelloWorld"
   match ==== "{{prefix_HelloWorld}}"

and:

   innerCapture === "Okay"
   match ==== "{{prefix_Okay}}"

Now, in python I have tried looking up docs on the re package

import re

Have tried doing something along the lines of:

match = re.search(r'pattern', string)
if match:
  print match.group()
  print match.group(1)

But it really doesn't make sense to me and doesn't work. For one, I'm not clear on what this group() concept means? And how am I to know if there is match.group(n)... group(n+11000)?

Thanks!

like image 798
John Tomson Avatar asked Jul 31 '13 07:07

John Tomson


People also ask

What can I use instead of replace in Python?

Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() .

Can Python be used to replace JavaScript?

No, Python cannot replace JavaScript because: (FRONT-END)JavaScript is browser-native and Python is not. (BACK-END) neither JavaScript nor Python is web-native. So, they will work in parallel.

Can Replace be used in string Python?

Python String replace() MethodThe replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

What is replace () in Python?

The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.


1 Answers

Python's re.sub function is just like JavaScript's String.prototype.replace:

import re

def replacer(match):
    return match.group(1).upper()

rawString = "{{prefix_HelloWorld}}   testing this. {{_thiswillNotMatch}} {{prefix_Okay}}"
result = re.sub(r'\{\{prefix_(.+?)\}\}', replacer, rawString)

And the result:

'HELLOWORLD   testing this. {{_thiswillNotMatch}} OKAY'

As for the groups, notice how your replacement function accepts a match argument and an innerCapture argument. The first argument is match.group(0). The second one is match.group(1).

like image 62
Blender Avatar answered Sep 23 '22 03:09

Blender