dudas
dudas

Reputation: 423

Convert single backslash to double backslash

I have a list containing directories: ("..\b\c.txt", "..\b\d.txt"). I was planning to use .split() method to have another list of the directory components separated by "\", but I'm not having success mostly due to "\" usage. Thus, the final result will be something like this ("a", "b, "c.txt") ...

I do understand \ being a escape character and the difficulties reported by this link, but I'm not understanding if it's possible to convert the entire list to raw string. Can anyone help?

files = ('..\..\data\User\level1\level2\sun.png','..\..\data\User\level1\level2\description.txt')

I was testing something like this:

str = files[0].split("\")

Desired output: a list containing:

('data', 'User', 'level1', 'level2', 'sun.jpg')

Upvotes: 0

Views: 1185

Answers (2)

Dan Getz
Dan Getz

Reputation: 9152

It turns out you're not quite there yet with understanding \ as an escape character. The escape characters are not extra characters in the actual string, they're extra characters in the source code.

To create a string that contains one \ character in Python, you can use \ as an escape character like this:

"\\"

There are 2 characters between the quotes in the source code, but in the actual string, there is only the "escaped character", which is the second \.

Note that "raw strings" are similar: the difference is in the source code, not the actual string. The following are equal:

"abc\\def"
r"abc\def"

What I do when I have doubts about things like this is play around in the interactive mode of the interpreter, and I'd suggest you do the same. For example, if you were unsure of what the real contents of a string like "abc\\def" really are, you could try print-ing it.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124978

If files is a literal, use raw literal notation then:

files = (
    r'..\..\data\User\level1\level2\sun.png',
    r'..\..\data\User\level1\level2\description.txt'
)

In this specific example, you managed to evade all of the known character escape sequences, but that was just lucky.

You can use "\\" to define a string with just a backslash:

files[0].split("\\")

Demo:

>>> files = (
...     r'..\..\data\User\level1\level2\sun.png',
...     r'..\..\data\User\level1\level2\description.txt'
... )
>>> files[0].split("\\")
['..', '..', 'data', 'User', 'level1', 'level2', 'sun.png']

If you wanted to split a path into parts, you probably should look at os.path.split() and the other functions in that module. Using such functions helps keep your code platform agnostic.

There is also os.sep and os.altsep, which would also help keep your code indepedendent of the OS.

Upvotes: 3

Related Questions