2017-07-11 5 views
4

私は一連の文字が繰り返される巨大な文字の行を持っています。行は:qwethisistheimportantpartqwethisisthesecondimportantpartPythonを使用して行の文字のセットの前に新しい行を追加するには

文字列にはスペースがありません。私は文字列 'qwe'の前に新しい行を追加して、すべての重要な部分を区別できるようにしたい。

出力:

qwethisistheimportantpart 
qwethisisthesecondimportantpart 

私は

for line in infile: 
    if line.startswith("qwe"): 
     line="\n" + line 

を使用してみました、あなたがre.split()を使用して、\nqweに参加することができます

+1

あなたが動作しないとはどういう意味ですか:だから何がそれを出力しない場合は、そう教えている場合、それは、エラーを与える、またはそれはあなたが望むものを出力しないん。 –

+0

これはうまくいくはずですが、 'line'をどのように処理しますか?それ以上のコーディングなしで入力ファイルに書き戻すつもりはありません。 –

+0

'qwe ...'は 'A55 ...'と何が関係していますか? –

答えて

5

str.replace()はあなたがやりたいことができます。

line = 'qwethisistheimportantpartqwethisisthesecondimportantpart' 
line = line.replace('qwe', '\nqwe') 
print(line) 
2

を動作していないよう:

import re 

s = "qwethisistheimportantpartqwethisisthesecondimportantpart" 

print '\nqwe'.join(re.split('qwe', s)) 

出力:

qwethisistheimportantpart 
qwethisisthesecondimportantpart 
2

私はあなたが言及したように、これはあなたのPython 2.7 実装

string = 'qwethisistheimportantpartqwethisisthesecondimportantpart' 
split_factor = 'qwe' 
a , b , c = map(str,string.split(split_factor)) 
print split_factor + b 
print split_factor + c 

するのに役立ちます。これは、同じ出力が得られ願っていますバディ。

出力:

qwethisistheimportantpart 
qwethisisthesecondimportantpart 
関連する問題