用一个反斜杠替换两个反斜杠 [英] Replace two backslashes with a single backslash

查看:95
本文介绍了用一个反斜杠替换两个反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个反斜杠替换一个带有两个反斜杠的字符串.但是replace似乎不接受'\\'作为替换字符串.这是解释器的输出:

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'

顺便说一句,我知道Windows路径需要包含两个反斜杠或一个正斜杠.我还是想替换它们以用于显示.

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.

推荐答案

您的输出没有双反斜杠.您正在查看的是字符串的 repr()值,该值显示带有转义的反斜杠.假设您的 temp_folder 具有两个反斜杠,则应改用:

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('\\\\', '\\'))

这将向您显示

C:\Users\User\AppData\Local\Temp

这也会删除引号.

但是您的 temp_folder 不太可能带有双反斜杠,并且显示上的这种差异可能使您认为 tempfile.gettempdir()的返回值中存在双反斜杠..正如@ Jean-Francois指出的那样,不应存在(至少在Windows上不存在).因此,您无需使用 .replace(),只需打印:

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)

这篇关于用一个反斜杠替换两个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆