0

In python, suppose there is an existing str pattern in following format,

pattern = r"\t Hello World!\n"

I want to substitute {r'\','t'} to tab character '\t', {r'\', '\n'} to newline character '\n' (and also other possible escape character). In other word, I want to get new_pattern in following format from pattern:

new_pattern = "\t Hello World!\n"

I can substitute them one by one:

new_pattern = re.sub(r'\t', '\t', pattern)
new_pattern = re.sub(r'\n', '\n', new_pattern)
...

or

new_pattern = re.sub(r'\\t', '\t', pattern)
new_pattern = re.sub(r'\\n', '\n', new_pattern)
...

But this is a little tedious, since there are many possible escape characters.
Is there any common way to "re-interpret" a str? (I don't know what should we call this kind of situation.)

Kera
  • 73
  • 6
  • Why do you have that string in the first place? Does that come from some wrong code that should be fixed instead? – Kelly Bundy Feb 02 '23 at 05:48
  • @KellyBundy, it is input, from command line or from a function parameter. This is a duplicated question. But I think it is hard to describle it. – Kera Feb 02 '23 at 06:14

0 Answers0