简体   繁体   中英

return os.getcwd problem with backslashes python

I've read a couple of threads regarding this topic, but nobody answered if there any way to normalize or to get rid of backslashes when using return function.

Since os.path.normpath doesn't seem to fix the return value of os.getcwd

import os

def p(): 
   var = os.getcwd()
   return os.path.normpath(var)
p()

Out[336]: 'C:\\x\\xx\\xxx\\xxx'

I really need to get the output in the following manner:

C:\x\xx\xxx\xxx

There's nothing you need to do to remove the extra slashes because they're not actually there. What you're seeing is just a quirk of how strings are stored or shown in Python because \ is the escape character in Python strings. In order to include a literal \ in a string, it must be escaped by another \ character, which is what you're seeing. If you print the output, you'll see that the extra (aka: escape slashes) are not shown:

>>> s = 'C:\\x\\xx\\xxx\\xxx'
>>> s
'C:\\x\\xx\\xxx\\xxx'
>>> print(s)
C:\x\xx\xxx\xxx
>>> len(s)
15
>>> s2 = '\\'
>>> len(s2)
1
>>> print(s2)
\

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