【发布时间】:2018-09-09 07:15:09
【问题描述】:
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()
如何只打印 5 行 zenpython。我试图在 readlines 中传递参数 5,但它不起作用。如果我使用 readlines() 我将得到如下输出。 ['\n', ' The Zen of Python, by Tim Peters\n', ' \n', ' 美丽胜于丑陋。\n', ' 显式胜于隐式。\n'].... .
但我只需要 5 行!
【问题讨论】:
-
不要为此使用
StringIO。分割线并切片。"\n".join(zenPython.splitlines()[:5])
标签: python