-1

Suppose I have a variable with a raw string assignment, as shown below.

TrackVariable = r'one\two\three'

TrackVariable will constantly change throughout the code; however, it will always be a raw string that may or may not contain any number of \ characters.

The raw string may even contain several \ characters in a row, as in the following example

TrackVariable = r'one\\\two\\\three'

If I manually name a file one\two\three.txt and drag it into a terminal window, it gets automatically formatted as one\\two\\three.txt

If I manually name a file one\\two\\three.txt and drag it into a terminal window, it gets automatically formatted as one\\\\two\\\\three.txt

And, finally, If I manually name a file one\\\two\\\three.txt and drag it into a terminal window, it gets automatically formatted as one\\\\\\two\\\\\\three.txt

How do I write a regex (or some other kind of code) that automatically re-formats the variables in the manner above. I assume that there is some kind of code that will append a \ after every occurrence of a \. How do I do this?

I am asking this question because I need to run a shell script in which TrackVariable will be part of a file path.

Edit: There are a number of other characters that must be escaped when running a shell script. Is there a simple way to automatically escape any characters that need escaping for a variable with a raw string assignment?

Here are the characters—with each one being separated by a space—that need escaping (I already know how to escape new lines)

| & ; ( ) < > ~ * ? ! $ # [ ] { } ' " `
Peter Schorn
  • 916
  • 3
  • 10
  • 20

1 Answers1

0

Ok, I can't believe I literally just figured it out, and it was much simpler than I thought. I literally spent hours trying trying to do this and by sheer coincidence found the answer a minute after posting the question.

import re

TrackVariable = r'D\o y\\ou g\\\et it y\\\\et?'

TrackVariable = re.sub(r'(\\)', r'\1\\', TrackVariable)

print(TrackVariable)

Prints --> D\\o y\\\\ou g\\\\\\et it y\\\\\\\\et?

Peter Schorn
  • 916
  • 3
  • 10
  • 20