-1

For example, if I want to add a space in-between all instances where I have one uppercase letter preceding a hyphen (A-, C-, etc...), then what function can I use to achieve this?

Alternatively, is there a way to get re.sub to output the pattern that was matched? :

>>> text = 'T- AB-'
>>> re.sub(r'\b[A-Z]-', 'what goes here?', text)
>>> text
'T - AB-'
yobogoya
  • 574
  • 7
  • 15

1 Answers1

0

You are looking to use capturing parenthesis and a \1

import re

text = 'T- AB-'
text = re.sub(r'\b([A-Z])-', r'\1 -', text)
print (text)

results:

T - AB-

That should do the trick. Whatever you capture in the ( ) can be referenced with \1. If you had a series of parenthesis each set can be referenced like \2, \3, etc. Good luck!

sniperd
  • 5,124
  • 6
  • 28
  • 44