【问题标题】:How to print just 5 lines in zenpython using readlines from IO.stringIO()如何使用 IO.stringIO() 中的 readlines 在 zenpython 中仅打印 5 行
【发布时间】: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 行!

【问题讨论】:

标签: python


【解决方案1】:

Python 之禅可作为 Python 内置模块使用,称为 this。导入后,它会将这首诗写入stdout。您可以将stdout 捕获到StringIO 变量中,然后只打印前5 行。以下适用于 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)

【讨论】:

  • 我觉得for line in zen.getvalue().splitlines()[:5]: print(line)会更好
  • 此语法不读取第一个空行并将输出列为 5 个单独的行。
【解决方案2】:

试试这个

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

虽然这是一种非正统的方式,它打印数据的前 100 个字节,在您的情况下是前 5 行,这将通过您的测试用例。

【讨论】:

    【解决方案3】:

    使用fp.readlines()[:5]

    readlines 返回一个列表。

    【讨论】:

    • 这对我有帮助。
    【解决方案4】:

    这是你考试题的答案。

    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) 
    

    【讨论】:

      【解决方案5】:
      fp = io.StringIO(zenPython)
      lines = []
      for each in fp.readlines():
             lines.append(each)
      return lines[0:5]
      

      【讨论】:

      • 虽然这段代码可能会解决问题,但一个好的答案应该解释代码的什么以及如何它有帮助
      • 这对我有帮助。
      猜你喜欢
      • 2023-01-26
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      相关资源
      最近更新 更多