-1

I'm not sure why this is happening so i don't know how to resolve it, if my question is unclear please ask and i will clarify. I am on a 32bit windows and running python2.7.

I have a list "commands"

commands = ['open', 'C:\\Users\\Me\\Videos\\manimmedia\\animations\\example_scenes\\1080p60\\SquareToCircle.mp4']

When i print commands[-1] i get

'C:\Users\Me\Videos\manimmedia\animations\example_scenes\1080p60\SquareToCircle.mp4'

The "\\" becomes single slash "\", but when i put it back in it becomes "\" again.

So when i run windows doesn't see that path when i run the code so it gives a "WindowsError: [Error 2] The system cannot find the file specified"

How do i replace double slash as single slash?

edit

When i include command as an argument, does it send the one with the single backslash or the one with the double slashes ? Basically is the string treated differently or are they both identical?

  • 2
    have you prefixing the python string with r? r'C:\Users\Me\Videos\manimmedia\animations\example_scenes\1080p60\SquareToCircle.mp4 will treat the string like a literal and ignore \U \M .. as escaped sequences – 138 Apr 07 '18 at 23:46
  • It's better not to use backslashes for [Windows paths in Python](/questions/2953834/windows-path-in-python). – Karl Knechtel Aug 06 '22 at 23:05
  • "So when i run windows doesn't see that path when i run the code so it gives a "WindowsError: [Error 2] The system cannot find the file specified"" No, if the file can't be found, it's for a different reason. Printing the string doesn't actually change the contents of the string. – Karl Knechtel Aug 06 '22 at 23:06

1 Answers1

3

In Python string literals, the backslash character has special meaning and is called the escape character. It is used to prefix what is called an 'escape sequence'. For example, \n is an escape sequence that inserts a newline character into your string. You can find out more about these sequences here: string-and-bytes-literals.

Sometimes like in your case, you want your string literal to include the actual backslash character. To do that you have to escape the backslash with another backslash like this: "\\". This results in a string containing a single backslash character, which is what you're observing.

If you don't want to have to insert double backslashes into all of your file paths, you can do what @138 suggested and use a raw string literal (prefixed with r: r'Raw string'). Raw string literals ignore anything that looks like an escape sequence, and treat each character as its literal value.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
DBrowne
  • 683
  • 4
  • 12