文字列を指定したパターンで置換する
文字列を指定したパターンで置換するには、reライブラリーをインポートします。
reライブラリーは、正規表現を利用した置換や検索などができます。
re.sub(パターン, 置換後の文字, 対象文字列)
連続した空白を,(カンマ)に置換するには、以下のようにします。
 実行例
>>> import re
>>> re.sub("[ ]+", ",", "AAA   BBB CCC")
AAA,BBB,CCC
置換を使ったPythonスクリプト
以下のPythonスクリプトは、空白区切りのファイルを読み込み、カンマ区切りにして書き込みます。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13  | 
						### インポート import re ### ファイル読み込み with open("rep.txt", "r") as f:     lines = f.readlines()     arr = []     for line in lines:         arr.append(re.sub("[ ]+", ",", line)) ### ファイル書き込み with open("rep.txt", "w") as f:     f.writelines(arr)  | 
					
 実行例
> type rep.txt
AAAA   19 179 88
BBBBBB 27 182 83
CC     29 180 83
> python rep.py
> type rep.txt
AAAA,19,179,88
BBBBBB,27,182,83
CC,29,180,83