1

I'm trying to replace backslashes or front slashes in a string with double backslashes. I've tried a couple of things but it doesn't seem to work.¨

My work so far:

string = 'C:\Users\Victor\Dropbox\Private\files\test.txt'

f = re.sub(r'[\\\/]', '\\\\', string)

This prints the string:

'C:\Users\Victor\Dropbox\Privateiles   est.txt'

But what i really want is a string that looks like this:

'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'

So that when i print the string it will look like the original

'C:\Users\Victor\Dropbox\Private\files\test.txt'

2 Answers 2

3

Just convert that string to a raw string:

>>> string = r'C:\Users\Victor\Dropbox\Private\files\test.txt'
>>> string
'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'
>>> print string
C:\Users\Victor\Dropbox\Private\files\test.txt
Sign up to request clarification or add additional context in comments.

3 Comments

What about strings as variables? string = raw_input('test: ') How do i make it interpret the string as a raw string?
I don't know if the edit was supposed to answer my question, but it did not. I still can't interpret user input as a raw string
+1 for raw string. :) @VictorVH if the answer is correct please consider accepting it.
1

If what you are really getting at is path manipulation, I'd just use the os module.

>>> s = r'C:\Users\Victor\Dropbox\Private\files\test.txt'
>>> import os
>>> os.path.normcase(s)
'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'

os.path.normcase

Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes. Raise a TypeError if the type of path is not str or bytes.

8 Comments

This makes sure to treat the string as a path or?
Please read the description I just added for normcase, it is safe to use as a path after using that function. Note that it is still a string literal as far as python is concerned
I just tried this. It returns an invalid string: c:\users\victor\dropbox\private ilewatcher\main.py
Hmm that is strange, I copy-pasted that right out of my IDLE terminal. What IDE are you using, and on what OS?
+1 for using os. Also, you may be interested in raw strings which don't interpret the backslash as an escape character. r"C:\Users\Victor\Dropbox\Private\files\test.txt".
|

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.