Output using readlines in Python

Stack Overflow Asked by Greg Atamian on November 14, 2020

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()

and the second case has the code,

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

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?

One Answer

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='atstringn'
>>> print(str(s))
a   string

>>> print(repr(s))

>>> print(s)
a   string

>>> print([s])

Answered by Mark Ransom on November 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP