2016-08-09 7 views
0

私は、この(AとBは人物であり、テキストの下に、それらの間の会話であると仮定)のようなテキストファイルに何か持っている:Python 3で新しい行 " n"を付けずに文字列をリストに追加するには?

[['A', 'Hello\n'], ['A', 'How are you?\n'], ['B', 'Hello\n'], ['B', 'I am good. Thanks and you?\n']] 
:私は、結果の下に返すリストにこの会話を追加

A: Hello 
B: Hello 
A: How are you? 
B: I am good. Thanks and you? 

私は、ループ内でこれらのコマンドを使用します。

new_sentence = line.split(': ', 1)[1] 
attendees_and_sentences[index].append(person) 
attendees_and_sentences[index].append(new_sentence) 

print(attendees_and_sentences) # with this command I get the above result 
print(attendees_and_sentences[0][1]) # if I run this one, then I don't get "\n" in the sentence. 

問題は、それらの「\ n」は私の結果画面上の文字です。どうすればそれらを取り除くことができますか?

ありがとうございます。

答えて

1

Pythonのrstrip関数を使用できます。例えば

>>> 'my string\n'.rstrip() 
'my string' 

そして、あなたは他の空白を維持しながら、末尾の改行をトリミングしたい場合は、あなたがそうのように、削除する文字を指定することができます。

>>> 'my string \n'.rstrip() 
'my string ' 
+0

はどうもありがとうございました。それは動作します! :) –

関連する問題