2012-07-27 23 views
1

我从一个函数的输出都是在单独的行上打破的值,我想将它变成一个列表。将文本转换为其行的列表

The Score 
Leon the Professional 
Iron Man 

我希望把它变成像一个列表:

movies= ['The Score', 'Leon the Professional', 'Iron Man'] 

我怎么能去这样做?

+4

通过“从功能输出”,你的意思是函数返回一个字符串?或打印到标准输出?或写入文件? – 2012-07-27 14:39:47

+0

@Matthew你的例子需要是有效的Python,否则我们只能猜测你有什么。 – jamylak 2012-07-27 14:40:28

+1

我们是否认为这是字符串'“Score \ nLeon专业\ nIron Man”'?只需使用's.split('\ n')'并阅读文档... – mgilson 2012-07-27 14:40:31

回答

9

假设你的输入是一个字符串。

>>> text = '''The Score 
Leon the Professional 
Iron Man''' 
>>> text.splitlines() 
['The Score', 'Leon the Professional', 'Iron Man'] 

有关splitlines()函数的更多信息。

+3

我应该更经常地使用'splitlines()'。我总是默认普通的'split()'。 – 2012-07-27 14:41:40

+0

出于好奇,你知道是否有理由更喜欢splitlines()到split('\ n')'? – mgilson 2012-07-27 14:42:02

+0

@mgilson看看这个[doc page](http://docs.python.org/library/stdtypes.html?highlight=splitlines#str.splitlines)的答案 - 我也很好奇:) – Levon 2012-07-27 14:43:49

0

假设你正在读行从文件:

with open('lines.txt') as f: 
    lines = f.readlines() 
    output = [] 
    for line in lines: 
     output.append(line.strip()) 
+1

'lines = map(str.strip,f)'是一个更短,更高效的方法。 list comp版本是:'lines = [line.strip()for line in f]' – jamylak 2012-07-27 15:02:29

+0

好点。谢谢 – clwen 2012-07-27 16:12:58