python 反斜杠变成人民币_python将反斜杠替换为斜杠

bd96500e110b49cbb3cd949968f18be7.png

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

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?

解决方案

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

There are two things to notice here:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值