0

Say I assign variable

x = '\\dnassmb1\biloadfiles_dev\Workday'
print(x)

Output:

'\\dnassmb1\x08iloadfiles_dev\\Workday'

I would like to know why it's changing to "x08.." specifically and how to avoid that automatic change and use string as it is. Thank you!

  • 1
    Related question - https://stackoverflow.com/questions/25065608/what-does-backward-slash-b-do-in-python – Mithilesh_Kunal Nov 15 '20 at 03:49
  • You can read the why in [String and bytes literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals): _The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character._ – tdelaney Nov 15 '20 at 03:59

2 Answers2

1

Use raw strings:

x = r'\\dnassmb1\biloadfiles_dev\Workday'

This will prevent python from treating your backslashes as escape sequences. See string and byte literals in the Python documentation for a full treatment of string parsing.

It's important to pay close attention to the difference between representation and value here. Just because a string appears to have four backslashes in it, doesn't mean that those backslashes are in the value of the string. Consider:

>>> x =  '\\dnassmb1\biloadfiles_dev\Workday'  # regular string
>>> y = r'\\dnassmb1\biloadfiles_dev\Workday'  # raw string
>>> print(x); print(y)
\dnassmbiloadfiles_dev\Workday
\\dnassmb1\biloadfiles_dev\Workday

Here, x and y are both just strings, once Python has parsed them. But even though the parts inside the quotes are the same, the bytes of the string are different. In y's case, you see exactly the number of backslashes you put in.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • Hey thank you for the answer! Output is: '\\\\dnassmb1\\biloadfiles_dev\\Workday' Is there a way to make it exactly '\\' slashes than 4 haha? – Tejas Krishna Reddy Nov 15 '20 at 03:50
  • 1
    Check out my answer – Irfan wani Nov 15 '20 at 03:51
  • @TejasKrishnaReddy I updated my answer -- I think you're confusing representation with value. If you want the exact string you entered, write it as a raw string, with exactly the number of backslashes you want out. – kojiro Nov 15 '20 at 03:57
1

You are doing wrong.Backslash has a different meaning in pyhton while using in strings. Backslashes are actually used to put some special character inside the string. If you want to get the above string printed;

x = '\\\dnassmb1\\biloadfiles_dev\\Workday'
print(x)

If you got this, i am using an extra backslash everywhere where i want a backslash to be printed. This is because the first backslash indicates that what ever is going to come after it is just a part of the string and has no special meaning.

Irfan wani
  • 4,084
  • 2
  • 19
  • 34