在python中获取第n行字符串

Ram*_*pte 9 python python-3.x

如何在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)


iru*_*var 5

功能方法

>>> 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)

  • @RamchandraApte,您要解析的字符串已经完全在内存中。此外,islice 适用于迭代器,与 readline 无关。 (2认同)
  • @RamchandraApte:此解决方案比您的解决方案快约 30%。如果您认为节省 80 字节的内存对您的应用程序至关重要,那就由您决定。cravoori 的解决方案更快的原因是大部分代码是用 C 执行的,而在您的解决方案中,更多的代码是用 Python 解释的。如果您想亲自查看,请使用 `dis` 模块来检查两者。 (2认同)

小智 5

`my_string.strip().split("\n")[-1]`
Run Code Online (Sandbox Code Playgroud)


Lev*_*von 3

从评论来看,这个字符串似乎非常大。如果数据太多而无法轻松放入内存,一种方法是逐行处理文件中的数据:

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是,当您完成或遇到异常时,它会自动为您关闭文件。

  • @RamchandraApte:Levon 的解决方案也适用于字符串,只需进行一点小小的更改。将 with 语句更改为 `with io.StringIO(data) as inf:` (2认同)