Reputation: 681
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.
Upvotes: 0
Views: 1761
Reputation: 1
This works for me
text = input('insert text')
list = text.split('\\')
print(list)
text2 = ''
for items in list:
if items != '':
text += items + '\\'
print(text2)
Upvotes: 0
Reputation: 76588
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)
Upvotes: 3