So lets say I receive a string of python code that looks as follows:
"def fib(num):\\n\\t#insert code here\\n\\tnumbers = [1, 2, 3]\\n\\tfor n in numbers:\\n\\t print(n + \\"\\\\n\\")"
I want to rewrite this string so that every time there is two backslashes, they get replaced by one backslash.
I have tried using code = re.sub(r'(\\)+', "\\", code)
but it gives me an error because the regex pattern ends with a backslash which is not allowed.
If I try to write code = re.sub(r'(\\)+', r'\\', code)
, however, it writes the backslash twice instead of once and I can't write r'\'
because python won't allow it. How would I go about doing this?
Edits with more info:
I'm using sys.stderr.write(repr(code) + '\n') to find the representation of the strings
Using the above string as the input, I get the following results:
Method One
code = re.sub(r'(\\\\)+', r"\\", code)
Yields: 'def fib(num):\\n\\t#insert code here\\n\\tnumbers = [1, 2, 3]\\n\\tfor n in numbers:\\n\\t print(n + \\"\\n\\")'
And writes to file: \n\t#insert code here\n\tnumbers = [1, 2, 3]\n\tfor n in numbers:\n\t print(n + \"\n\")
Method Two
code = code.replace(r'\\', '\\')
Yields: 'def fib(num):\\n\\t#insert code here\\n\\tnumbers = [1, 2, 3]\\n\\tfor n in numbers:\\n\\t print(n + \\"\\n\\")'
And writes to file: \n\t#insert code here\n\tnumbers = [1, 2, 3]\n\tfor n in numbers:\n\t print(n + \"\n\")
Method Three
code = re.sub(r'(\\)+', "\\", code)
Yields Error: sre_constants.error: bad escape (end of pattern) at position 0
Method Four
code = re.sub(r'(\\)+', r'\\', code)
Yields: 'def fib(num):\\n\\t#insert code here\\n\\tnumbers = [1, 2, 3]\\n\\tfor n in numbers:\\n\\t print(n + \\"\\n\\")'
And writes to file: \n\t#insert code here\n\tnumbers = [1, 2, 3]\n\tfor n in numbers:\n\t print(n + \"\n\")