Python replace, using patterns in array -
i need replace things in string using array, can this:
array = [3, "$x" , "$y", "$hi_buddy"] #the first number number of things in array string = "$xena here $x , $y."
i've got array things replace things, let's called rep_array.
rep_array = [3, "a", "b", "c"]
for replacement use this:
for x in range (1, array[0] + 1): string = string.replace(array[x], rep_array[x])
but result is:
string = "aena here , b."
but need lonely $x not $x in word. result should this:
string = "$xena here , b."
note that:
- all patterns in
array
start$
. - a pattern matches if matches whole word after
$
;$xena
doesn't match$x
,foo$x
would match. $
can escaped@
, should not matched (for example$x
not match@$x
)
use regular expression wraps source text whitespace look-behind , \b
anchor; make sure include start of string too:
import re pattern, replacement in zip(array[1:], rep_array[1:]): pattern = r'{}\b'.format(re.escape(pattern)) string = re.sub(pattern, replacement, string)
this uses re.escape()
ensure regular expression meta characters in pattern escaped first. zip()
used pair patterns , replacement values; more pythonic alternative range()
loop.
\b
matches @ position word character followed non-word character (or vice versa), word boundary. patterns end in word character, makes sure patterns match if next character not word character, blocking $x
matching inside $xena
.
demo:
>>> import re >>> array = [3, "$x" , "$y", "$hi_buddy"] >>> rep_array = [3, "a", "b", "c"] >>> string = "$xena here $x , $y. foo$x matches too!" >>> pattern, replacement in zip(array[1:], rep_array[1:]): ... pattern = r'{}\b'.format(re.escape(pattern)) ... string = re.sub(pattern, replacement, string) ... >>> print string $xena here , b. fooa matches too!
Comments
Post a Comment