Python-string-splitlines

提供:Dev Guides
移動先:案内検索

Python String splitlines()メソッド

説明

Python文字列メソッド* splitlines()*は、string内のすべての行を含むリストを返します。オプションで改行を含めることもできます(numが指定され、trueの場合)

構文

以下は、* splitlines()*メソッドの構文です-

str.splitlines()

パラメーター

  • Keepends -これはオプションのパラメーターで、その値がtrueの場合、改行が必要な場合も出力に含まれます。

次の例は、splitlines()メソッドの使用法を示しています。

#!/usr/bin/python

str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines( )
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )

上記のプログラムを実行すると、次の結果が生成されます-

['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

このメソッドにパラメータとして「True」を渡すと、出力に改行が含まれます。

#!/usr/bin/python

str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines(True)
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )

出力

上記のプログラムを実行すると、次の結果が生成されます-

['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']