简体   繁体   English

将\\放在行尾在python中有什么作用?

[英]What does placing \ at the end of a line do in python?

I'm looking at the following piece of code: 我正在看下面的代码:

totalDistance += \
      GetDistance(xCoords[i], yCoords[i],
                         xCoords[i+1], yCoords[i+1])

and can't understand what += \\ means? 并且不明白+= \\是什么意思?

\\ at the end of a line just indicates it will be continued on the next line as otherwise that ( totalDist += ) would raise an error... (also important to note that there can be nothing after the slash ... not even whitespace) \\只是表明它将在下一行继续,否则( totalDist += )会引发错误...(同样重要的是要注意,斜杠后不能有任何内容...甚至不空格)

+= just adds and assigns back +=只是添加并分配回来

x = 1
x += 1 # x is now 2  (same as  x = x + 1)

The \\ escapes the line return immediately following it (there should not be any character between the \\ and the implicit \\n ). \\将紧随其后的行返回转义(在\\和隐式\\n之间不应有任何字符)。

There are also a few other exceptions; 还有其他一些例外。 new lines are ignored when enclosed in the matching pairs of the following: 当包含在以下匹配对中时,将忽略新行:

  • []
  • ()
  • {}

In other words, the following are equivalent: 换句话说,以下是等效的:

a= [1,2,3]
a = [1,
     2,
     3]

The combination \\ followed by newline means line continuation. \\后跟换行符的组合表示行继续。 You can think of the \\ as escaping the newline, so that it doesn't have it's usual meaning of "line ending". 您可以将\\视为转义符,以免它没有“换行符”的通常含义。

In Python, you can often arrange the code so that \\ is unnecessary, eg. 在Python中,您通常可以安排代码,这样\\就不必要了,例如。

totalDistance += GetDistance(
                     xCoords[i], yCoords[i],
                     xCoords[i+1], yCoords[i+1])

here, the newlines don't end the line because they are inside the () 在这里,换行符不结束行,因为它们在()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM