difference after remove

Peter peter at commonlawgov.org
Mon Oct 24 15:01:38 EDT 2005


Shi Mu wrote:

>Is there any difference if I remove the '/'
>  
>
I will assume you mean "\", not "/". ;)

>from the following statement?
>intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
>             [1,2,5,3,9,1,1,1,9,1],\
>             [0,0,5,1,1,1,9,7,7,7]]
>print intMatrix2
>  
>
>I removed one '\' and it still works.
>So what is the use of '\'?
>  
>
Python normaly executes a statement as soon as a new line is given.

A backslash is for "line continuation", it tells Python to ignore the 
new line (instead of executing the current line as it would normaly).
If line-continuation is used in a string it will also ignore the new 
line (handy for when the theres to much on the line already but you 
don't want to break the string into two peices).

In some situations (inside functions calls, tuples, lists) this is not 
needed.


**** Some examples of using line-continuation****

# -------------------------------------------------
## Example 1

# With line-continuation:
 >>> print "a"\
... "b"\
... "c"
abc

# Without line-continuation:
 >>> print "a"
a
 >>> "b"
'b'
 >>> "c"
'c'

# ---------------------------------------------------
## Example 2

# With line-continuation:
 >>> print "Hello, \
... World!"
Hello, World!

# Without line-continuation:
 >>> print "Hello,
  File "<stdin>", line 1
    print "Hello,
                 ^
SyntaxError: EOL while scanning single-quoted string
 >>> World!"
  File "<stdin>", line 1
    World!"
         ^
SyntaxError: invalid syntax

# -----------------------------------------
## Example 3

# With line-continuation:
 >>> print """Hello, \
... World!"""
Hello, World!

# Without line-continuation:
 >>> print """Hello,
... World!"""
Hello,
World!

# -----------------------------------------
## Example 4

# With line-continuation:
 >>> [1,\
... 2,\
... 3]
[1, 2, 3]

# Without line-continuation:
 >>> [1,
... 2,
... 3]
[1, 2, 3]

 >>>

**** / End examples ****

HTH,
Peter




More information about the Python-list mailing list