2011-06-16 31 views
1

有一個字符串:製作名單

str = "first line\n xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz" 

我需要的列表,包括兩個要素:第一行和其他一切:

list = ['first line\n', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz'] 

如何我可以做嗎?

回答

8
print str.split('\n', 1) 
['first line', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz'] 

的第一要素,如果你想保留它做沒有「\ n」的

splited = str.partition('\n') 
print [splited[0] + splited[1], splited[2]] 
['first line\n', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz'] 

不要命名您的字符串str,因爲你會遮蔽STR型,無論是使用「真」作爲參數傳遞給splitlines列表list :)

+0

但與此'\ n'將不會在結果列表中的第一個元素的一部分 – sateesh 2011-06-16 10:52:43

+0

@sateesh:是的,我看到了,只是更正:) – mouad 2011-06-16 10:54:02

+0

Upvoted。我以前沒有看到分區,很酷的功能+很好的使用它。您可能需要在使用\ r而不是\ n的舊mac上進行調整\ n – 2011-06-16 11:12:42

2
>>> str = "first line\n xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz" 
>>> str.split('\n', 1) 
['first line', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz'] 
+0

將str用作變量,但仍然是+1,不是一個好主意。 – utdemir 2011-06-16 10:54:36

+0

我認爲他希望\ n留在第一行的末尾 – 2011-06-16 11:02:22

+0

@utdemir好點。通常不會,只是跟隨他的變量名稱。儘管如此,應該對此有所記錄。 – Blair 2011-06-16 11:59:13

2
>>> s = "first line\n xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz" 
>>> s=s.splitlines(True) 
>>> s=[s[0],"".join(s[1:])] 
>>> s 
['first line\n', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz'] 

指定它應該「保持結束「

+0

我編輯變量名稱從「str」到「s」以避免陰影。有沒有人投票給我,因爲這 – 2011-06-16 10:59:47

+0

+1,你不配被downvoted IMO :) – mouad 2011-06-16 11:06:04