简体   繁体   中英

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: 在此处输入图片说明

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?

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

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