Summary of python Method for Inputting Multiline Strings
- 2021-07-06 11:23:10
- OfStack
Enter multiple lines of string in Python:
Method 1: Use 3 quotation marks
>>> str1 = '''Le vent se l è ve, il faut tenter de vivre.
The wind is blowing, so we have to work hard to survive.
Even if there is a high wind, life will never give up.) '''
>>> str1
'Le vent se l è ve, il faut tenter de vivre. \n The wind is blowing, so we have to work hard to survive. \n Even if there is a high wind, life will never give up.) '
>>> print(str1)
Le vent se l è ve, il faut tenter de vivre.
The wind is blowing, so we have to work hard to survive.
Even if there is a high wind, life will never give up.)
Method 2: Use a backslash
>>> str2 = 'Le vent se l è ve, il faut tenter de vivre. \
The wind is blowing, so we have to work hard to survive. \
Even if there is a high wind, life will never give up.) '
>>> str2
'Le vent se l è ve, il faut tenter de vivre. The wind is blowing, so we have to work hard to survive. Even if there is a high wind, life will never give up.) '
Method 3: Use parentheses
>>> str3 = ('Le vent se l è ve, il faut tenter de vivre.'
' The wind is blowing, so we have to work hard to survive. '
' Even if there is a high wind, life will never give up.) ')
>>> str3
'Le vent se l è ve, il faut tenter de vivre. The wind is blowing, so we have to work hard to survive. Even if there is a high wind, life will never give up.) '
Extension:
Problem
There is a string that is very long. How to write it in multiple lines?
Solve
Method 1
Use a continuation character:
sql = "select * "\
" from a "\
" where b = 1"
However, the higher version of python may not support this method, and it is not concise to add a continuation character at the end of the line every time.
Method 2
Use parentheses:
sql = ("select *"
" from a "
" where b = 1")
Strings in parentheses can be written in multiple lines. It is recommended.