pythonで複数行の文字列を入力する方法をまとめました。


Pythonに複数行の文字列を入力します。
方法一:三引用符を使う

>>> str1 = '''Le vent se lève, il faut tenter de vivre. 

   ,      。

(     ,     。)'''

 

>>> str1

'Le vent se lève, il faut tenter de vivre. 
, 。
( , 。)' >>> print(str1) Le vent se lève, il faut tenter de vivre. , 。 ( , 。)
方法二:バックスラッシュを使う

>>> str2 = 'Le vent se lève, il faut tenter de vivre. \

   ,      。\

(     ,     。)'

 

>>> str2

'Le vent se lève, il faut tenter de vivre.    ,      。(     ,     。)'
方法3:小かっこを使う

>>> str3 = ('Le vent se lève, il faut tenter de vivre.'

'   ,      。'

'(     ,     。)')

 

>>> str3

'Le vent se lève, il faut tenter de vivre.   ,      。(     ,     。)'
拡張子:
問題
長い文字列がありますが、どうやって複数行書きますか?
解決
方法1
次の行を使う:

sql = "select * "\
" from a "\
" where b = 1"
しかし、高バージョンのpythonはこの方式をサポートしていないかもしれません。また、毎回最後の行に続く行を追加します。簡潔ではありません。
方法2
括弧を使う:

sql = ("select *"
" from a "
" where b = 1")
括弧内の文字列は複数行に書くことができます。おすすめです。