简体   繁体   中英

How do i replace \\ with / in python 3?

I have a part in my program that requires working with directories.My current code is:

path = os.path.join('C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup')

Variable path prints: 'C:Users\\\\name\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup'.

My question is how can I make var path print 'C:Users/name/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'

Use the .replace() method of strings

"C:Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup".replace('\\', '/')

#'C:Users/name/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'

As suggested in the comments the system does it.

You are better off changing os.sep or os.path.sep but however you can do this.

>>> os.path.sep = '\\'
>>> os.path.sep
'\\'              #we have changed the separator
>>> os.sep.join(['C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup'])
'C:\\Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'

But you can simply use this though,

>>> '\\'.join(['C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup'])
'C:\\Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'

Well both are the same as mentioned in the comments!.

Also os.path.join does not depend upon os.sep or os.path.sep so changing them doesn't prove any effect.

您可以将'\\\\'替换为'/'

path = path.replace('\\','/')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM