0

What's the best alternative function of Lua's global pattern substitution function string.gsub(s, pattern, function) in Python? e.g.

> string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
bnanaa  2

UPDATE: I'd like to implement a complex function during pattern substitution in Python like Lua's string.gsub, which can be implemented by Python's re.sub with function or lambda expr.

abuccts
  • 339
  • 4
  • 12
  • `re.sub` is the function you want. – Alex Hall Jul 08 '17 at 09:01
  • `re.sub`, maybe? `re.sub('(a)(n)', r'\2\1', 'banana')` What do you mean by *"best"*? – jonrsharpe Jul 08 '17 at 09:02
  • @jonrsharpe : I'd like to implement a complex function during pattern substitution in Python like Lua's `string.gsub`, which can also be implemented by Python's `re.sub` with [function](https://stackoverflow.com/a/17136150/7630831) or [lambda expr](https://stackoverflow.com/a/18737927/7630831). – abuccts Jul 09 '17 at 08:29

1 Answers1

2

As string.gsub(s, pattern, replace [, n]) returns a pair of values, the modified string and the number of substitutions made, in Python, you need to use re.subn:

re.subn(pattern, repl, string, count=0, flags=0)
Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

See a Python demo:

import re
print (re.subn("(a)(n)", r"\2\1", "banana"))
# => ('bnanaa', 2)

And you also may use an anonymous method (or a lambda expression for simpler scenarios) as a replacement argument:

print (re.subn("(a)(n)", lambda m: "{}{}".format(m.group(2), m.group(1)), "banana"))
# => ('bnanaa', 2)

See another Python demo.

NOTE: If you need no number of replacements made, use a mere re.sub.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563