Replacing double slash with single backslash

I recently encountered something for the first time in python, if I execute the following

usrPath=os.environ['USERPROFILE']

in Maya script editor or Eyeon Fusion Console it returns path with single backslash but if i exewcute this code in directly in python interpreter i get double slashes … Why does this happens :(:

i want to perform a file copy operation into system folder so I can get path from os.environ[‘USERPROFILE’] but should I do it with double slash or if it wont do how should I replace double backslash with the single one ?

It’s returning the same string value in either case; the only difference is in how it’s being printed. Try this directly in a python interpreter / IDLE (after importing os):

os.environ['USERPROFILE']
# 'C:\\Documents and Settings\\username'

print os.environ['USERPROFILE']
# C:\Documents and Settings\username

The explicit print gives you the human-readable representation of your string. If you leave it out, the interpreter automatically calls repr, giving you a completely unambiguous, behind-the-scenes form.

The reason for the difference, in this case, is that a single backslash is used as an escape character, so that you can type in special values like \r,
, , etc. Because of this, if you’re typing in the literal value for a string and you want to include a backslash, you have to escape it too, like so: \

Long story short, if you’re getting the path from os.environ, it’s already correctly formatted and you don’t have to worry about the slashes. If you’re entering a literal string value that represents a path, you need to escape your backslashes. Here’s an example that constructs the path to a subdirectory based on the current value of USERPROFILE:


import os

SUBDIRECTORY_RELATIVE_PATH = 'My Documents\\someStuff\\otherFolder'

userPath = os.environ['USERPROFILE']
subdirectoryPath = os.path.join(userPath, SUBDIRECTORY_RELATIVE_PATH)

if not os.path.isdir(subdirectoryPath):
    os.makedirs(subdirectoryPath)
    
print subdirectoryPath
# prints: C:\Documents and Settings\username\My Documents\someStuff\otherFolder

print repr(subdirectoryPath)
# prints: 'C:\\Documents and Settings\\username\\My Documents\\someStuff\\otherFolder'

edit: This image probably does a better job explaining it (hooray for syntax highlighting):

This is a classic pain in the ass for all of us, so lots of people default to using right slashes instead. However you can also use the literal operator ‘r’ in front of our string if you want to get a literal rather than a bunch of stupid escape chars:


path = r'C:\path	o\file.txt'

fwiw most uses (os.path, opening files, etc) on windows work fine with right slashes.