what is the purpose of the \ because they do not affect the function of the code?

72 Views Asked by At

I have a university assignment to create a noughts&crosses/tictactoe game from a given template and this below was part of it:

board = [['1','2','3'],\
         ['4','5','6'],\
         ['7','8','9']]

Whether those backslashes are present or not it doesnt affect the function of the code as the list gives the same printed output and behaves in the same way so I'm just curious as to what their purpose is?

2

There are 2 best solutions below

2
tdelaney On

The backslash escapes the next character. Since the next character is a newline, the python parser would work as if the newline wasn't there. But a newline is completely harmless in this context, so its distracting and pointless to do it here.

A different case is string concatentation

foo = "bar"\
      "baz"

Without the backslash this would be a two lines of code - in this case resulting in an indentation error. But since the newline has been escaped, its the same as

foo = "bar"    "baz"

and python will concatenate those into a single string during compile.

NOTE

Although there are many escape sequences in string literals, this is the only escape allowed outside of them. Its called a "line continuation character" (or Explicit line joining) because it suppresses normal line termination rules in the python lexer.

Alternately, there is also Implicit line joining:

Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.

Since your list definition already follows implicit line joining rules, there is no need to add the explicit rule.

0
Davis Herring On

Their purpose is consistency: they let you join physical lines when balanced delimiters aren’t available, and it’s simpler to let them be used anywhere than to allow them only when no other option exists.