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
88 views
in Technique[技术] by (71.8m points)

python - Why do backslashes appear twice?

When I create a string containing backslashes, they get duplicated:

>>> my_string = "whydoesithappen?"
>>> my_string
'why\does\it\happen?'

Why?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

What you are seeing is the representation of my_string created by its __repr__() method. If you print it, you can see that you've actually got single backslashes, just as you intended:

>>> print(my_string)
whydoesithappen?

The string below has three characters in it, not four:

>>> 'a\b'
'a\b'
>>> len('a\b')
3

You can get the standard representation of a string (or any other object) with the repr() built-in function:

>>> print(repr(my_string))
'why\does\it\happen?'

Python represents backslashes in strings as \ because the backslash is an escape character - for instance, represents a newline, and represents a tab.

This can sometimes get you into trouble:

>>> print("thisextis
otwhatitseems")
this    extis
otwhatitseems

Because of this, there needs to be a way to tell Python you really want the two characters rather than a newline, and you do that by escaping the backslash itself, with another one:

>>> print("this\textiswhatyou\need")
thisextiswhatyou
eed

When Python returns the representation of a string, it plays safe, escaping all backslashes (even if they wouldn't otherwise be part of an escape sequence), and that's what you're seeing. However, the string itself contains only single backslashes.

More information about Python's string literals can be found at: String and Bytes literals in the Python documentation.


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

...