[Python]文字列を行ごとに分割するには?

python

どうも、ちょげ(@chogetarou)です。

文字列を行ごとに分割する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

文字列を行ごとに分割するには、splitlines()を使います。

具体的には、文字列からsplitlines()を呼び出します。

lines = text.splitlines()

splitlines()は、呼び出した文字列を行ごとに分割したリストを返します。

使用例

text1 = """Hello,
World.
Python Programming."""

text2 = "My\nName\nIs\nChoge"

lines1 = text1.splitlines()
lines2 = text2.splitlines()

print(lines1)
print(lines2)
出力: 
['Hello,', 'World.', 'Python Programming.']
['My', 'Name', 'Is', 'Choge']

コメント

タイトルとURLをコピーしました