0

I write the below code in pycharm IDE. While hitting enter after hello (inside single quoted string), pycharm automatically adds a backslash and blank single quoted string. I want to know how python executes the code given below and what is the purpose to add backslash and a single quoted blank string.

s = 'Hello' \

' '
Avish
  • 4,516
  • 19
  • 28
  • Does this help: https://stackoverflow.com/questions/16060238/what-is-the-purpose-of-a-backslash-at-the-end-of-a-line – jdaz Jun 06 '20 at 13:29
  • If backslash escapes newline character then why a blank single quoted string is added automatically. Also print('hello\\n') can print hello\n. Here also we add another backslash to escape newline character. But if we try to print s then it only display hello on screen.Why? – akku coder Jun 06 '20 at 13:41

1 Answers1

0

In Python:

  • If a line ends with a backslash, the current statement or expression is not terminated and instead carry on to the next line (i.e. an escaped linebreak does not affect parsing the way a regular linebreak does)
  • Two adjacent string literals are concatenated ("ab" "cd" == "abcd")

Combining these two properties allows you to span a single string literal over multiple lines, by closing a string literal using a quote, terminating the line with a backslash, then writing another string literal on the next line:

my_string = 'this is my string literal, ' \
'it continues on the next line'

>>> print my_string
"this is my string literal, it continues on the next line"

PyCharm detects you hitting Enter inside the string literal, and breaks the string literal for you. Try writing a single long string literal, then positioning the cursor somewhere in the middle of it and hitting Enter - PyCharm would split the string literal into two separate but adjacent string literals, on two different lines, with a backslash at the end of the first line.

Avish
  • 4,516
  • 19
  • 28