Issue
I want to replace a string with two backslashes with single backslashes. However replace doesn't seem to accept '\\' as the replacement string. Here's the interpreter output:
>>> import tempfile
>>> temp_folder = tempfile.gettempdir()
>>> temp_folder
'C:\\Users\\User\\AppData\\Local\\Temp'
>>> temp_folder.replace('\\\\', '\\')
'C:\\Users\\User\\AppData\\Local\\Temp'
BTW, I know that Windows paths need to contain either double backslashes or a single forward slashes. I want to replace them anyway for display purposes.
Solution
Your output doesn't have double backslashes. What you are looking at is the repr()
value of the string and that displays with escaped backslashes. Assuming your temp_folder
would have double backslashes, you should instead use:
print(temp_folder.replace('\\\\', '\\'))
and that will show you:
C:\Users\User\AppData\Local\Temp
which also drops the quotes.
But your temp_folder
is unlikely to have double backslashes and this difference in display probably got you thinking that there are double backslashes in the return value from tempfile.gettempdir()
. As @Jean-Francois indicated, there should not be (at least not on Windows). So you don't need to use the .replace()
, just print:
print(temp_folder)
Answered By - Anthon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.