2017-01-20 11 views
0

「文字列」のスライス方法を理解してから、「文字列」を見つけた後に行全体を取得します。 これは私がこれまでに何をすべきかです:文字列の終わりから行末までの文字列の終わりまでのスライシング

content.txt : 
#Try to grab this line start 
#Try to grab this line 1 
#Try to grab this line 2 
#Try to grab this line 3 
#Try to grab this line 4 
#Try to grab this line 5 
#Try to grab this line 6 
#Try to grab this line end 
#Try to grab this line 7 
#Try to grab this line 8 

私のスクリプト:

​​

出力result.txt:

start 
    #Try to grab this line 1 
    #Try to grab this line 2 
    #Try to grab this line 3 
    #Try to grab this line 4 
    #Try to grab this line 5 
    #Try to grab this line 6 
    #Try to grab this line 

私は必要な出力は次のようになります。

#Try to grab this line start 
#Try to grab this line 1 
#Try to grab this line 2 
#Try to grab this line 3 
#Try to grab this line 4 
#Try to grab this line 5 
#Try to grab this line 6 
#Try to grab this line end 

ありがとう、私は私のexplを願っていますanationは明らかに どんな助けも大いに評価されるだろう!あなたが行うことができ

+0

を、あなたは包括的、開始と終了の区切り文字の間のすべての行をキャプチャする方法を知りたいですか? – ThisSuitIsBlackNot

+0

はいライン全体 – alanyukeroo

+0

関連:http://stackoverflow.com/q/7559397、http://stackoverflow.com/q/7098530 – ThisSuitIsBlackNot

答えて

0

:つまり

with open(fname) as f: 
    content = f.readlines() 
# you may also want to remove whitespace characters like `\n` at the end of each line 
content = [x.strip() for x in content] 
# Get the id of the line with "start" 
start_id = [id for id in range(len(content)) if "start" in content[id]][0] 
# Get the id of the line with "end" 
stop_id = [id for id in range(len(content)) if "end" in content[id]][0] 
# Slice our content 
sliced = content[start_id : stop_id+1] 
# And finally, to get your output : 
for line in sliced : 
    print line 
# Or to a file : 
make = open('D:\PROJECT\Python\result.txt', "w") 
for line in sliced : 
    make.write("%s\n" % line) 
+0

本当にありがとう! もっと詳しく説明したい場合、これらのスクリプト( "%s \ n"%line)は何を意味していますか? – alanyukeroo

+0

これは、元の罰金から新しい行を書き込むことを意味します。 "%s"部分はあなたの文字列の位置です。そして、この文字列を "%line"で置き換えます。これは、 "%s"が "line"の値を取ることを意味します。 "\ n"はファイルに新しい行を追加するためのものです。 – iFlo

関連する問題