2016-05-01 16 views
1

私はPythonを使ってファイルを読み込もうとしています。 この私のファイルtest.txtの:Pythonではどのようにline.rstrip()を使用しますか?

Hello World 
My name is Will 
What's your name? 

これは私のpythonのコードです:

fhand = open('test.txt') 
for line in fhand: 
    line.rstrip() 
    print line 

私はline.rstrip()を使用するかどうかに関係なく、出力は次のように常にある:

Hello World 

My name is Will 

What's your name? 

このようにrstrip()を使用して空行なしで出力するにはどうすればよいですか?

Hello World 
My name is Will 
What's your name? 

答えて

4
line = line.rstrip() 

それ以外の場合、この行は変更されず、その代わりに取り除か1の古い行を使用しています。

3
line.rstrip() 

ここでは、ストリッピングされた文字列を取得しますが、値を保存していません。

のデモを見てみましょうline = line.rstrip()

line.rstrip()を置き換えます

>>> string = "hello " 
>>> string.rstrip() 
'hello' 
>>> string 
'hello ' 
>>> string = string.rstrip() 
>>> string 
'hello' 
>>> 
2

パイソンの文字列(および他の言語を)不変で、一度、彼らは変更することはできません作成したという意味なので、基本的にline.rstrip()は新しい文字列を作成しますストライプされた内容のインスタンス。

あなたは印刷する前にそれにあなたの変数を設定することができます。

line = line.rstrip() 

同じことが他の文字列関数などのために行く:ストリップ、小文字、大文字などとスライス例:行[1:]

へ他のタイプがこのように動作するか調べる:https://en.wikibooks.org/wiki/Python_Programming/Data_Types#Mutable_vs_Immutable_Objects