Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use line.rstrip() in Python?

Tags:

python

I am trying to read a file using Python. This the my file test.txt:

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

This is my python code:

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

No matter whether I use line.rstrip(), The output is always as following:

Hello World

My name is Will

What's your name?

How can I output without the empty line using rstrip() like this?

Hello World
My name is Will
What's your name?
like image 453
Shiyu Lian Avatar asked May 01 '16 16:05

Shiyu Lian


People also ask

What does line line Rstrip () do?

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

What does input () Strip () do in Python?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.


2 Answers

line.rstrip() does not change the old variable, it returns the stripped value of the old variable and you have to reassign it in order for the change to take effect, like:

line = line.rstrip()

Otherwise the line isn't changed and it uses the old line instead of the stripped one.

like image 182
Sven Hakvoort Avatar answered Sep 17 '22 23:09

Sven Hakvoort


 line.rstrip()

Here you do get the stripped string, but you are not storing the value.

Replace line.rstrip() with line = line.rstrip()

Let's see the demo:

>>> string = "hello    "
>>> string.rstrip()
'hello'
>>> string
'hello    '
>>> string = string.rstrip()
>>> string
'hello'
>>> 
like image 41
Ahsanul Haque Avatar answered Sep 18 '22 23:09

Ahsanul Haque