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

python

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

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

スポンサーリンク

方法

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

文字列を改行ごとに分割する方法は、2つあります。

splitlines()

1つは、splitlines()メソッドを使う方法です。

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

split_text = text.splitlines()

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

使用例

text = """AB
CD
E
FGH
IJK
L"""

split_text = text.splitlines()

print(split_text)
print(type(split_text))
出力:
['AB', 'CD', 'E', 'FGH', 'IJK', 'L']
<class 'list'>

split()

もう1つは、split()メソッドを使う方法です。

まず、文字列からsplit()メソッドを呼び出します。

そして、split()メソッドの引数に「\n」を指定します。

split_text = text.split("\n")

上記のsplit()メソッドは、呼び出した文字列を改行ごとに分割したリストを返します。

使用例

text = """AB
CD
E
FGH
IJK
L"""

split_text = text.split("\n")

print(split_text)
print(type(split_text))
出力:
['AB', 'CD', 'E', 'FGH', 'IJK', 'L']
<class 'list'>

まとめ

文字列を改行ごとに分割する方法は、次の2つです。

  • splitlines()メソッドを使う方法
    split_text = text.splitlines()
  • split()メソッドを使う方法
    split_text = text.split("\n")

コメント

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