Why does PyCharm use double backslash to indicate

2019-04-09 01:02发布

问题:

For instance, I write a normal string and another "abnormal" string like this:

Now I debug it, finding that in the debug tool, the "abnormal" string will be shown like this:

Here's the question:

Why does PyCharm show double backslashes instead of a single backslash? As is known to all, \' means '. Is there any trick?

回答1:

What I believe is happening is the ' in your c variable string needs to be escaped and PyCharm knows this at runtime, given you have surrounded the full string in " (You'll notice in the debugger, your c string is now surrounded by '). To escape the single quote it changes it to \', but now, there is a \ in your string that needs escaping, and to escape \ in Python, you type \\.

EDIT Let me see if I can explain the order of escaping going on here.

  1. "u' this is not normal" is assigned to c
  2. PyCharm converts the string in c to 'u' this is not normal' at runtime. See how, without escaping the 2nd ', your string is now closed off right after u.
  3. PyCharm escapes the ' automatically for you by adding a slash before it. The string is now 'u\' this is not normal'. At this point, everything should be fine but PyCharm may be taking an additional step for safety.
  4. PyCharm then escapes the slash it just added to your string, leaving the string as: 'u\\' this is not normal'.

It is likely a setting inside PyCharm. Does it cause an actual issue with your code?