Long character strings may be assigned to variables in SQL operations, etc., but there are mainly the following two methods.
--Parentheses ()
→ Use implicit line continuation
--Use of triple quotes '''
and " ""
[Kosei Kitahara's Works: Google Python Style Guide] According to (http://works.surgo.jp/translation/pyguide.html#id73), the former is recommended. The latter is because if you indent as follows, the space will be included in the character string.
-->
()
→ Use implicit line continuationtext = ('a' #No comma required
'b')
print(text) # ab
#Same as below
text = 'ab'
#Note 1:If you add a comma, it will be recognized as a tuple of two strings.
text = ( 'a',
'b')
print(text) # ('a', 'b')
#Note 2:I don't know if it's practical, but it can be put together in one line
text = ('a' 'b')
print(text) # ab
#Note 3:The practicality of this is also unknown, but it is also possible to use line continuation and tuple together.
text = ('a', 'b'
'c')
print(text) # ('a', 'bc')
\ N
is required for line breaks.
This method is also effective not only for character string assignment but also for function import.
(Do you use it naturally when the number of function arguments increases?).
from some.deep.module.inside.a.module import (
a_nice_function, another_nice_function, yet_another_nice_function)
[Python Hitchhiking Guide-Code Style] (https://python-guideja.readthedocs.io/ja/latest/writing/style.html#id8)
When using this together with format, you need to write .format ()
together at the end:
text = ( 'a = {0}, '
'b = {1}'.format(1, 2))
print(text) # a = 1, b = 2
Writing .format ()
on each line will result in SyntaxError
:
#The following is a Syntax Error:becomes invalid syntax
text = ( 'a = {}, '.format(1)
'b = {}'.format(2))
If the contents of .format ()
become too complicated, is it better to create a list of strings → join withstr.join ()
?
-->
'''
and " ""
It is also called "triple quotation mark" or "triple quotation mark". In this case, the line breaks at the line break in the code.
text = '''hello
world'''
print( text )
# hello
# world
#Same as below
text = 'hello\nworld'
#Note 1:If you don't want to break\use
text = '''hello\
world'''
print( text ) # helloworld
#Note 2:If you break the beginning and the end, the line break will be included.
text = '''
hello
world
'''
print( text )
# (new line)
# hello
# world
# (new line)
#Note 3:If you try to match the indentation on the code, the space will be treated as a string.
text = '''hello
world'''
print( text )
# hello
# world
Let's programming: multi-line string description using triple quotes note.nkmk.me: String generation in Python (quotes, str constructor)
Recommended Posts