readlines gives me additional linebreaks python2.6.5

前端 未结 3 463
粉色の甜心
粉色の甜心 2021-01-21 08:33

I have problems with the following code:

file = open(\"file.txt\", \"r\")
lines = file.readlines()
print lines[0]
print lines[1]
print lines[2]
file.close()
         


        
3条回答
  •  遇见更好的自我
    2021-01-21 09:10

    print adds a newline. Strip the newline from the line:

    print lines[0].rstrip('\n')
    print lines[1].rstrip('\n')
    print lines[2].rstrip('\n')
    

    If you are reading the whole file into a list anyway, an alternative would be to use str.splitlines():

    lines = file.read().splitlines()
    

    which by default removes the newlines from the lines at the same time.

提交回复
热议问题