1

I'm struggling with a following piece of code:

import re 

datain = "u_func/u_cpu/uSC300"

elements = ["cpu","123"]

SEARCH = r"([0-9_/])%s([0-9_/])" % elements[0]
REPLACE = r'\1%s\2' % elements[1]
dataout = re.sub(SEARCH, REPLACE, datain, flags=re.IGNORECASE)

print datain
print dataout

The output of the code is following:

u_func/u_cpu/uSC300
u_func/uJ3/uSC300

Please note that cpu is not substituted by 123, but with something else.

If I change the LINE 5 to:

REPLACE = r'\1 %s\2' % elements[1]

Then the correct string is inserted:

u_func/u_cpu/uSC300
u_func/u_ 123/uSC300

But there is a space added as well. Of course, I don't want the space.

Question: How to substitute the correct string, without the space being added?

Boris L.
  • 936
  • 2
  • 12
  • 28
  • 1
    It has been asked a lot of times. Use `r'\g<1>%s\g<2>' % elements[1]` – Wiktor Stribiżew Jun 16 '17 at 17:22
  • 1
    I'm surprised this produces `uJ3` instead of either an error message or the result you expected. – user2357112 Jun 16 '17 at 17:24
  • Thanks, I have been searching the web for hours, but could not find anything. Maybe I don't know the right terminology to formulate the right question... – Boris L. Jun 16 '17 at 17:26
  • Perl solves the group number vs adjacent literal number by allowing the group number to be encased in `{x}`, while python has it's own form `\g<2> ` –  Jun 16 '17 at 18:00

0 Answers0