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?
The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
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.
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'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With