Python 正则表达式替换反斜杠或前斜杠

标签 python regex string replace

我正在尝试用双反斜杠替换字符串中的反斜杠或前斜杠。我已经尝试了几件事,但似乎没有用。¨

我目前的工作:

string = 'C:\Users\Victor\Dropbox\Private\files\test.txt'

f = re.sub(r'[\\\/]', '\\\\', string)

这会打印字符串:

'C:\Users\Victor\Dropbox\Privateiles   est.txt'

但我真正想要的是一个看起来像这样的字符串:

'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'

这样当我打印字符串时,它看起来就像原来的一样

'C:\Users\Victor\Dropbox\Private\files\test.txt'

最佳答案

只需将该字符串转换为原始字符串:

>>> string = r'C:\Users\Victor\Dropbox\Private\files\test.txt'
>>> string
'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'
>>> print string
C:\Users\Victor\Dropbox\Private\files\test.txt

关于Python 正则表达式替换反斜杠或前斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769242/

相关文章:

java - 在 Java 中使用正则表达式在第一个逗号之后和两个大写字母和一个逗号之前提取字符串

正则表达式匹配模式,但排除一组单词

javascript - localeCompare() 在移动浏览器上的奇怪行为

python - 操作 tensorflow 代码来添加不同的层

pythonic 方式 : vars in dict

regex - 查找命令与 'regex' 匹配不工作

swift - 快速删除 Unicode U+2018 左单引号,如“Ali to Ali”

.net - 使用正则表达式将字符串映射到功能

python - Visual Studio Code : Intellisense not working

python - 将颜色图添加到图表中