-1

I have a string, in which I'd like to substitute each [ by [[] and ] by []] (at the same time). I thought about doing it with re.sub:

re.sub(r'(\[|\])', '[\1]', 'asdfas[adsfasd]')
Out: 'asdfas[\x01]adsfasd[\x01]'

But I'm not getting the desired result -- how do I make the re.sub consider \1 in the pattern as the first matched special group?

sygi
  • 4,557
  • 2
  • 32
  • 54

1 Answers1

1

You should use r prefix for your replacing regex as well, otherwise \1 will be interpreted as a hex literal:

In [125]: re.sub(r'(\[|\])', r'[\1]', 'asdfas[adsfasd]')

Out[125]: 'asdfas[[]adsfasd[]]'
Mazdak
  • 105,000
  • 18
  • 159
  • 188