2009-07-09 20 views
1

コード内で長い1行の文字列を壊し、残りのコードをインデントしたままにするにはどうすればよいですか? PEP 8にはこのケースの例はありません。Pythonの長い一行文字列最大行長を超えない

正しいouptutが、妙にインデント:

if True: 
    print "long test long test long test long test long \ 
test long test long test long test long test long test" 

>>> long test long test long test long test long test long test long test long test long test long test 

悪い出力が、コードの見え方:

if True: 
    print "long test long test long test long test long \ 
    test long test long test long test long test long test" 

>>> long test long test long test long test long  test long test long test long test long test long test 

うわー、速い答えの多くを。ありがとう!

答えて

6
if True: 
    print "long test long test long test long test long"\ 
    "test long test long test long test long test long test" 
+3

参考資料は次のとおりです:http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation –

27

隣接する文字列は、コンパイル時に連結されています

if True: 
    print ("this is the first line of a very long string" 
      " this is the second line") 

出力:

this is the first line of a very long string this is the second line 
+0

なぜこれが大幅に投票されたのですか? – JcMaco

+1

これは、現在の受け入れられている回答よりも多くの情報を持っている可能性が高いため、Pythonのほうが多いためです(PEP 8の質問:「長い行を折り返す方法は、Pythonの暗黙の行継続を括弧、中かっこで囲むことです)。いくつかの個人的な好みも関係するかもしれませんが、答えの著者として、私はそれについてコメントすることはできません。 –

+0

@ノア、もうあなたに同意できません。私はそれが受け入れられた唯一の理由は、最後の行のインデントと@ JcMacoのオリジナルポストとの一致であると思います。それは自明であり、説得力がありません。実際、PEP 8スタイルも好きです。申し訳ありませんが、私はその瞬間に寝る必要があり、私の壊れた英語に追加情報を追加していませんでした。 – sunqiang

2

あなたは、このように別の文字列を結合するために、末尾のバックスラッシュを使用することができます。

if True: 
    print "long test long test long test long test long " \ 
      "test long test long test long test long test long test" 
-6
if True: 
    print "long test long test long test "+ 
    "long test long test long test "+ 
    "long test long test long test " 

など。

+8

このコードには構文エラーがあります。他の回答を追加する必要があります。兆候は余分です。 –

0

トリプルクォートを推薦する人はいないのはなぜですか?

print """ blah blah 
      blah ..............""" 
+2

あなたが必要とする特別な書式設定なしで2番目と3番目の間に巨大なスペースが残るためです。 – Unknown

+0

また、括弧の考え方は他のものに一般化しているので...例えば、関数への引数や長い数式など。括弧はより多くのpythonicです。 – Tom

+0

ここの例はGoogleピトンスタイルガイドでご覧ください:http://code.google.com/p/soc/wiki/PythonStyleGuide#Line_length – Tom

関連する問題