2024-04-25 15:23:11 发布
网友
在Python 3中,如何获得字符串的nth行? 例如
getline("line1\nline2\nline3",3)
使用stdlib/builtin函数有什么方法可以做到这一点吗? 我更喜欢Python 3中的解决方案,但Python 2也不错。
功能方法
>>> import StringIO >>> from itertools import islice >>> s = "line1\nline2\nline3" >>> gen = StringIO.StringIO(s) >>> print next(islice(gen, 2, 3)) line3
请尝试以下操作:
s = "line1\nline2\nline3" print s.splitlines()[2]
使用字符串缓冲区:
import io def getLine(data, line_no): buffer = io.StringIO(data) for i in range(line_no - 1): try: next(buffer) except StopIteration: return '' #Reached EOF try: return next(buffer) except StopIteration: return '' #Reached EOF
功能方法
请尝试以下操作:
使用字符串缓冲区:
相关问题 更多 >
编程相关推荐