Python正则表达式替换反斜杠或前斜杠 [英] Python regex replace backslash or frontslash

查看:99
本文介绍了Python正则表达式替换反斜杠或前斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我目前的工作:

string = 'C:\Users\Victor\Dropbox\Private\files\test.txt'f = re.sub(r'[\\\/]', '\\\\', 字符串)

这将打印字符串:

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

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

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

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

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

解决方案

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

<预><代码>>>>字符串 = r'C:\Users\Victor\Dropbox\Private\files\test.txt'>>>细绳'C:\\Users\\Victor\\Dropbox\\Private\\files\\test.txt'>>>打印字符串C:\Users\Victor\Dropbox\Private\files\test.txt

I'm trying to replace backslashes or front slashes in a string with double backslashes. I've tried a couple of things but it doesn't seem to work.¨

My work so far:

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

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

This prints the string:

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

But what i really want is a string that looks like this:

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

So that when i print the string it will look like the original

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

解决方案

Just convert that string to a raw string:

>>> 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正则表达式替换反斜杠或前斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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