如何在Python 3中获得字符串的第n行?例如
getline("line1\nline2\nline3",3)
Run Code Online (Sandbox Code Playgroud)
有没有办法使用stdlib/builtin函数?我更喜欢Python 3中的解决方案,但Python 2也没问题.
Mar*_*air 21
请尝试以下方法:
s = "line1\nline2\nline3"
print s.splitlines()[2]
Run Code Online (Sandbox Code Playgroud)
功能方法
>>> import StringIO
>>> from itertools import islice
>>> s = "line1\nline2\nline3"
>>> gen = StringIO.StringIO(s)
>>> print next(islice(gen, 2, 3))
line3
Run Code Online (Sandbox Code Playgroud)
从评论来看,这个字符串似乎非常大。如果数据太多而无法轻松放入内存,一种方法是逐行处理文件中的数据:
N = ...
with open('data.txt') as inf:
for count, line in enumerate(inf, 1):
if count == N: #search for the N'th line
print line
Run Code Online (Sandbox Code Playgroud)
使用enumerate()可以为您提供要迭代的对象的索引和值,并且您可以指定起始值,因此我使用 1 (而不是默认值 0)
使用的优点with是,当您完成或遇到异常时,它会自动为您关闭文件。