どうも、ちょげ(@chogetarou)です。
文字列(string)の改行を置換する方法を紹介します。
方法

文字列(string)の改行を置換する方法は、2つあります。
replace()
ひとつは、replace()を使う方法です。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に改行コード、第2引数に置換後の文字列を指定します。
#text=対象の文字列, new=置換後の文字列
result = text.replace('\n', new)
上記のreplace()は、文字列の改行を置換した結果を返します。
使用例
text = "He\nllo\n,Wo\nrl\nd"
result = text.replace('\n', '*')
print(result)
出力:
He*llo*,Wo*rl*d
sub()
もうひとつは、sub()を使う方法です。
まず、reをインポートします。
import re
reからsub()を呼び出します。
そして、re.sub()の第1引数に改行コード、第2引数に置換後の文字列を指定します。
re.sub()の第3引数に対象の文字列を指定します。
#text=対象の文字列, new=置換後の文字列
result = re.sub('\n', new, text)
上記のsub()は、文字列の改行を置換した結果を返します。
使用例
import re
text = """AB
CD
E
FGH
IJK
L"""
result = re.sub('\n', '*', text)
print(result)
出力:
AB*CD*E*FGH*IJK*L
まとめ
文字列(string)の改行を置換する方法は、次の2つです。
- replace()を使う方法
result = text.replace('\n', new)
- sub()を使う方法
result = re.sub('\n', new, text)
コメント