python将反斜杠替换为斜杠 [英] python replace backslashes to slashes

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

问题描述

如何在字符串'pictures\12761_1.jpg'中转义反斜杠?

How can I escape the backslashes in the string: 'pictures\12761_1.jpg'?

我知道原始字符串.例如,如果我从xml文件中获取'pictures\12761_1.jpg'值,如何将str转换为raw?

I know about raw string. How can I convert str to raw if I take 'pictures\12761_1.jpg' value from xml file for example?

推荐答案

您可以将字符串.replace()方法与rawstring一起使用.

You can use the string .replace() method along with rawstring.

Python 2:

>>> print r'pictures\12761_1.jpg'.replace("\\", "/")
pictures/12761_1.jpg

Python 3:

>>> print(r'pictures\12761_1.jpg'.replace("\\", "/"))
pictures/12761_1.jpg

这里有两件事要注意:

  • 首先通过将r放在 细绳.如果您不这样做,这里将出现Unicode错误.
  • 而且在replace方法的第一个参数内给出了两个反斜杠.原因是反斜杠是与其他字母一起用作转义序列的文字.现在,您可能想知道什么是转义序列.因此,转义序列是在字符串文字或字符中使用时不表示自身的字符序列.它由两个或多个以反斜杠开头的字符组成.像'\ n'代表换行符,类似地,也有很多.因此,要转义反斜杠本身(通常是转义序列的开始),我们可以使用另一个反斜杠对其进行转义.
  • Firstly to read the text as a drawstring by putting r before the string. If you don't give that, there will be a Unicode error here.
  • And also that there were two backslashes given inside the replace method's first argument. The reason for that is that backslash is a literal used with other letters to work as an escape sequence. Now you might wonder what is an escape sequence. So an escape sequence is a sequence of characters that doesn't represent itself when used inside string literal or character. It is composed of two or more characters starting with a backslash. Like '\n' represents a newline and similarly there are many. So to escape backslash itself which is usually an initiation of an escape sequence, we use another backslash to escape it.

我知道第二部分有点令人困惑,但我希望这是有道理的.

I know the second part is bit confusing but I hope it made some sense.

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

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