Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace, using patterns in array

I need to replace some things in a string using an array, they can look like this:

array = [3, "$x" , "$y", "$hi_buddy"]
#the first number is number of things in array
string = "$xena is here $x and $y."

I've got another array with things to replace those things, let's say its called rep_array.

rep_array = [3, "A", "B", "C"]

For the replacement I use this:

for x in range (1, array[0] + 1):
  string = string.replace(array[x], rep_array[x])

But the result is:

string = "Aena is here A and B."

But I need to much only lonely $x not $x in another word. Result should look like this:

string = "$xena is here A and B."

Note that:

  • all patterns in array start with $.
  • a pattern matches if it matches the whole word after $; $xena doesn't match $x, but foo$x would match.
  • $ can be escaped with @ and than it should not be matched (for example $x does not match @$x)

1 Answers

this is not a direct answer to your question, but as I guess you'll get other solutions hacking around \b, I'm going to suggest you a more pythonic solution:

rep_dict = {'x': 'A', 'y': 'B', 'hi_buddy': 'C'}
string = '{xena} is here {x} and {y}'

print string.format(rep_dict)

but here, it will raise a KeyError for missing xena in rep_dict, which can be solved by answers to that question, using a defaultdict or a formatter you may prefer depending on your use case.

The problem with using $, is that it is not trivial to make something that matches that does not define the real boundary. Most languages using $ variables apply it to the next one character, using a boundary on larger characters (those are shells and makefiles), i.e. ${xena}. Languages like Perl use a grammar to define the context of a $ variable, and I guess they may use regexps as well in the tokenizer.

That's why in python, we only use formatting operators to mark the boundaries of the variable {} in the string, not having useless $ so we do not have to deal with ambiguities ($xena => ${x}ena or ${xena}?).

HTH

like image 182
zmo Avatar answered Jan 24 '26 22:01

zmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!