fox
fox

Reputation: 16536

python: replace a double \\ in a path with a single \

Working with a string:

"D:\\Whatever\\Folder\\Etc 1"

which I eventually want to turn into

"D:\Whatever\Folder\Etc 1"

I'm using the following Python:

ln=line[:-1].replace('\n','').replace('\r','').replace("\\\\","\\").rstrip(' ')

but it's not doing the trick -- is there a better practice for cutting the slashes out?

Upvotes: 4

Views: 1343

Answers (3)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58291

I think you are printing as raw string, see:

>>> "D:\\Whatever\\Folder\\Etc 1"
'D:\\Whatever\\Folder\\Etc 1'
>>> 
>>> print "D:\\Whatever\\Folder\\Etc 1"
D:\Whatever\Folder\Etc 1

Also check this '\\' is single char (first \ is escape char):

>>> "D:\\Whatever\\Folder\\Etc 1"[2]
'\\'

Is it what you wants ?

As you commented:

>>> len("D:\\Whatever\\Folder\\Etc 1")
24
>>> "D:\\Whatever\\Folder\\Etc 1"[23]
'1'
>>> 

length counts single char, as I said '\\' is a single char. Length of your string is 24 and last char at 23 is 1.

more clear:

>>> len('\\')
1

see also this example:

>>> 'a\nb'
'a\nb'              # single \
>>> print 'a\nb'
a                   # no \ but, b printed on new line
b

Upvotes: 4

Eike
Eike

Reputation: 2223

The canonical way is to use slash (/) characters instead of backslash (\) in file names. This avoids confusion, and makes your program portable. All file related functions in Python work with slashes, and Windows accepts them too.

The concrete issue is escaping. The backslash is treated as a special character in regular Python strings. It is used to express characters that are difficult to express otherwise. For example "\n" is a newline character "\t" is a tabulator. Therefor to express a backslash itself, you have to write "\\", this is a single backslash character.

If you really have to deal with backslashes use raw strings. This is an alternative way to write string literals, where the backslash has no special meaning. They are created like so:

s = r"foo\bar"

Note the r at the start. Variable s is a string with 7 characters.

But there's a slight complication: r"foo\" is a syntax error! A raw string can not end with a backslash.

Upvotes: 2

neilr8133
neilr8133

Reputation: 152

Expanding on what Eike said: Use / instead of \ to A) Simplify writing and B) make sure your code still works if run on a non-Windows system.

Also, look at the functions in os.path, for example:

>>> print os.path.abspath('d:/foo/bar/baz')
d:\foo\bar\baz
>>> print os.path.abspath('c:\\program files\\')
c:\program files

Upvotes: 1

Related Questions