有没有办法从Python中的多行字符串中获取指定的行?例如:
>>> someString = 'Hello\nthere\npeople\nof\nEarth'
>>> aNewString = someString.line(1)
>>> print aNewString
there
我想制作一个简单的“解释器”样式脚本,循环遍历它所馈送的文件的每一行。
答案 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']