'How to print just 5 lines in zenpython using readlines from IO.stringIO()

import io

def main():
    zenPython = '''
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    '''
    fp = io.StringIO(zenPython)

    #Add Implementation step here
    li=fp.readlines()

how to print just 5 lines of zenpython. i have tried to pass argument 5 in readlines but its not working. if i use readlines() i will get the output as below. ['\n', ' The Zen of Python, by Tim Peters\n', ' \n', ' Beautiful is better than ugly.\n', ' Explicit is better than implicit.\n'].....

but i need only 5 line!



Solution 1:[1]

Use fp.readlines()[:5].

readlines returns a list.

Solution 2:[2]

This is a answer for your exam question.

fp = io.StringIO(zenPython) // assign teh string to fp variable
zenlines=fp.readlines()[:5] //only 5 lines of the string is read from the variable
print(zenlines) //print the output
return(zenlines) 

Solution 3:[3]

fp = io.StringIO(zenPython)
lines = []
for each in fp.readlines():
       lines.append(each)
return lines[0:5]

Solution 4:[4]

The Zen of Python is available as a python builtin module, called this. When imported, it writes the poem to stdout. You can capture stdout to a StringIO variable, then print only the first 5 lines. The following works on python3:

import contextlib
from io import StringIO
zen = StringIO()

with contextlib.redirect_stdout(zen):
    import this

for i, line in enumerate(zen.getvalue().split('\n')):
    if i < 5:
      print(line)

Solution 5:[5]

try this

li=fp.readlines(100)
print(li)
return(li)

while this is an unorthodox way that prints first 100 bytes of your data which in your case is first 5 lines and that will pass your testcases.

Solution 6:[6]

fp = io.StringIO(zenPython)

li=fp.readlines(100)

return fp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geisterfurz007
Solution 2 Manivannan KG
Solution 3 Arijit
Solution 4 match
Solution 5 geisterfurz007
Solution 6 Divyani