2

I am using stings to hold filepaths in python and I want to replace the single backslash with a double backslash for use in cmd but I have a problem where due to the backslash it is changing a letter into a special characters. For example:

string="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
print(sting)

outputs:

"C:\Program Files (x86)\Mozilla Firefox\x0cirefox.exe"

when I want it to output

"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

This problem continues when I want to replace the "\" with a "\\" using

string.replace("\\","\\\\")

Instead of it outputing:

"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"

It outputs:

"C:\\Program Files (x86)\\Mozilla Firefox\xocirefox.exe"
1
  • 2
    Oblig. xkcd Commented Apr 17, 2017 at 12:45

2 Answers 2

1

Use raw strings:

>>> string=r"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
>>>print(string)
C:\Program Files (x86)\Mozilla Firefox\firefox.exe

>>> print(string.replace('\\','\\\\'))
C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe
Sign up to request clarification or add additional context in comments.

Comments

1

You can use raw strings to simply ignore the backslash.

>>> string=r"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
>>> print(string)
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

You can find out more about this in the Python documentation for lexical analysis

5 Comments

Thanks this has fixed my problem i will accept this answer when it allows me to.
how can you convert a variable holding a string into a raw string?
The "raw string" is just a syntax feature for typing string literals in the source code. At Python object level there's no difference.
the probelm i have is that i need to take the string in the question and use it in the cmd using subprocess but it needs to be used in a variable which will can only be assinged as a normal string but if i try to replace the slashes i encounter the problem above so i need a way to tell python the variable should be a raw string when im calling it.
So there's another problem... Perhaps you could write another question describing the exact situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.