简体   繁体   中英

How use line.rstrip() in 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?

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.

 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'
>>> 

Strings in python (and other languages) are immutable, meaning once created they cannot be modified, so essentially line.rstrip() creates a new string instance with the stripped content.

You can set your variable to it before printing:

line = line.rstrip()

Same goes for other string functions eg: strip, lowercase, uppercase etc. and slicing eg: line[1:]

To find out what other types behave this way check out: https://en.wikibooks.org/wiki/Python_Programming/Data_Types#Mutable_vs_Immutable_Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM