Greg Atamian
Greg Atamian

Reputation: 11

Output using readlines in Python

I was wondering if anyone had an answer for this. In the image the top case has the code,

output of the two different lines of code from below: enter image description here

def stats ():
    inFile = open('textFile.txt', 'r')
    line = inFile.readlines()
    print(line[0])

and the second case has the code,

def stats ():
    inFile = open('textFile.txt', 'r')
    line = inFile.readlines()
    print(line[0:1])

instead of going to the next iteration and printing it, it just spits out the iteration, now populated with all the \t and the end of line character \n. Can anyone explain why this is happening?

Upvotes: 0

Views: 96

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308111

In the first case you're printing a single line, which is a string.

In the second case you're printing a slice of a list, which is also a list. The strings contained within the list use repr instead of str when printed, which changes the representation. You should loop through the list and print each string separately to fix this.

>>> s='a\tstring\n'
>>> print(str(s))
a   string

>>> print(repr(s))
'a\tstring\n'

>>> print(s)
a   string

>>> print([s])
['a\tstring\n']

Upvotes: 1

Related Questions