Home  >  Article  >  Backend Development  >  What is the python line continuation character?

What is the python line continuation character?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-20 16:30:0550049browse

Straddle literal strings can be expressed in the following ways. Use the line continuation character, that is, use a backslash after the last character of each line to indicate that the next line is a logical continuation of the previous line.

The following uses \n to add a new line:

What is the python line continuation character?

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n 意味着新行
>>> s  # 不使用 print(), \n 包含在输出中
'First line.\nSecond line.'
>>> print(s)  # 使用 print(), \n 输出一个新行
First line.
Second line.

The following uses a backslash (\) to continue a line:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
 significant."
 
print(hello)

Related recommendations: "Python Video Tutorial"

Note that the newline character must still be represented by \n - the newline character after the backslash is discarded. The above example will output the following:

This is a rather long string containing
several lines of text just as you would do in C.
    Note that whitespace at the beginning of the line is significant.

Alternatively, the string can be enclosed by """ (three double quotes) or ''' (three single quotes). When using triple quotes, the newline character is not required Escape, they will be included in the string. The following example uses an escape character to avoid an unwanted blank line at the beginning.

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

The output is as follows:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

If we use a "raw" string, then \n will not be converted into a newline, and the backslash at the end of the line, as well as the newline character in the source code, will be included in the string as data. For example:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)

will output:

This is a rather long string containing\n\
several lines of text much as you would do in C.

The above is the detailed content of What is the python line continuation character?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn