-1

The program should get each of these punctuation characters replaced by that character surrounded by two spaces.

I tried this:

sent = re.sub('[!,\'!?.]',' \1 ', sent)    

but it just printed some weird icon instead of those punctuation characters

This was done using python 3.

farbiondriven
  • 2,450
  • 2
  • 15
  • 31

2 Answers2

2

The string "\1" was interpreted as ascii codepoint 1 \x01. To prevent this from happening, use the raw string r' \1'. Also, to use a back-reference, you should use parentheses. This is the result:

>>> sent = "!,\'!?."
>>> sent = re.sub(r'([!,\'!?.])',r' \1 ', sent)
>>> sent
" !  ,  '  !  ?  . "
Zweedeend
  • 2,565
  • 2
  • 17
  • 21
0

As per my original comment, your replacement is \1 but you never created a capture group. Surround your regex in () as the following suggests. Also, you need to escape \ or make it a raw string.

re.sub(r"([,'!?.])", r' \1 ', sent) 

See code in use here

ctwheels
  • 21,901
  • 9
  • 42
  • 77