读取字符串的第x行?

2024-09-27 09:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
get nth line of string in python

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

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

我想制作一个简单的“解释器”风格的脚本,循环遍历它输入的文件的每一行。在


Tags: of方法字符串inhellogetstringline
3条回答

请记住,我们可以^{}字符串来形成lists。在本例中,您希望使用换行符\n作为分隔符进行拆分,因此如下所示:

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

还有一个使用通用换行符作为分隔符的^{}函数:

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

在换行符上拆分字符串:

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

相关问题 更多 >

    热门问题