读取字符串x行?

时间:2012-10-03 21:08:21

标签: python

  

可能重复:
  get nth line of string in python

有没有办法从Python中的多行字符串中获取指定的行?例如:

>>> someString = 'Hello\nthere\npeople\nof\nEarth'
>>> aNewString = someString.line(1)
>>> print aNewString
there

我想制作一个简单的“解释器”样式脚本,循环遍历它所馈送的文件的每一行。

4 个答案:

答案 0 :(得分:4)

>>> someString = 'Hello\nthere\npeople\nof\nEarth'
>>> someList = someString.splitlines()
>>> aNewString = someList[1]
>>> print aNewString
there

答案 1 :(得分:2)

请记住,我们可以split字符串形成lists。在这种情况下,您希望使用换行符\n作为分隔符进行拆分,如下所示:

someString = 'Hello\nthere\npeople\nof\nEarth'
print someString.split('\n')[lineindex]

还有一个splitlines函数使用通用换行符作为分隔符:

someString = 'Hello\nthere\npeople\nof\nEarth'
print someString.splitlines()[lineindex]

答案 2 :(得分:2)

在换行符上拆分字符串:

>>> someString = 'Hello\nthere\npeople\nof\nEarth'
>>> someString.split('\n')
['Hello', 'there', 'people', 'of', 'Earth']
>>> someString.split('\n')[1]
'there'

答案 3 :(得分:1)

In [109]: someString = 'Hello\nthere\npeople\nof\nEarth'

In [110]: someString.split("\n")[1]
Out[110]: 'there'

In [111]: lines=someString.split("\n")

In [112]: lines
Out[112]: ['Hello', 'there', 'people', 'of', 'Earth']