Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - python replace backslashes to slashes

How can I escape the backslashes in the string: 'pictures12761_1.jpg'?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Python 2:

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

Python 3:

>>> print(r'pictures12761_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 ' ' 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...