用一个反斜杠替换两个反斜杠
Replace two backslashes with a single backslash
我想用一个反斜杠替换一个有两个反斜杠的字符串。但是 replace 似乎不接受 '\\' 作为替换字符串。这是解释器输出:
>>> import tempfile
>>> temp_folder = tempfile.gettempdir()
>>> temp_folder
'C:\Users\User\AppData\Local\Temp'
>>> temp_folder.replace('\\', '\')
'C:\Users\User\AppData\Local\Temp'
顺便说一句,我知道 Windows 路径需要包含双反斜杠或单正斜杠。出于显示目的,我还是想更换它们。
您的输出没有双反斜杠。您正在查看的是字符串的 repr()
值,它显示有转义的反斜杠。假设您的 temp_folder
有双反斜杠,您应该改用:
print(temp_folder.replace('\\', '\'))
这会告诉你:
C:\Users\User\AppData\Local\Temp
这也会删除引号。
但是您的 temp_folder
不太可能有双反斜杠,这种显示差异可能让您认为 tempfile.gettempdir()
的 return 值中有双反斜杠。正如@Jean-Francois 指出的那样,不应该存在(至少在 Windows 上不存在)。所以你不需要使用 .replace()
,只需打印:
print(temp_folder)
这对我有用
text = input('insert text')
list = text.split('\')
print(list)
text2 = ''
for items in list:
if items != '':
text += items + '\'
print(text2)
我想用一个反斜杠替换一个有两个反斜杠的字符串。但是 replace 似乎不接受 '\\' 作为替换字符串。这是解释器输出:
>>> import tempfile
>>> temp_folder = tempfile.gettempdir()
>>> temp_folder
'C:\Users\User\AppData\Local\Temp'
>>> temp_folder.replace('\\', '\')
'C:\Users\User\AppData\Local\Temp'
顺便说一句,我知道 Windows 路径需要包含双反斜杠或单正斜杠。出于显示目的,我还是想更换它们。
您的输出没有双反斜杠。您正在查看的是字符串的 repr()
值,它显示有转义的反斜杠。假设您的 temp_folder
有双反斜杠,您应该改用:
print(temp_folder.replace('\\', '\'))
这会告诉你:
C:\Users\User\AppData\Local\Temp
这也会删除引号。
但是您的 temp_folder
不太可能有双反斜杠,这种显示差异可能让您认为 tempfile.gettempdir()
的 return 值中有双反斜杠。正如@Jean-Francois 指出的那样,不应该存在(至少在 Windows 上不存在)。所以你不需要使用 .replace()
,只需打印:
print(temp_folder)
这对我有用
text = input('insert text')
list = text.split('\')
print(list)
text2 = ''
for items in list:
if items != '':
text += items + '\'
print(text2)