2012-01-01 627 views
2

對於Python,我知道「\ n」會跳到字符串中的下一行,但我想要做的是將字符串中的每個「,」替換爲「\ n」。那可能嗎?我對Python很陌生。Python和換行符

回答

3

試試這個:

text = 'a, b, c' 
text = text.replace(',', '\n') 
print text 

對於列表:

text = ['a', 'b', 'c'] 
text = '\n'.join(text) 
print text 
+0

謝謝!!!!!我像一個魅力工作! – user1114215 2012-01-01 15:18:46

+0

不客氣:)如果答案有用,請考慮接受 – 2012-01-01 15:20:30

+0

這可能適用於列表嗎? – user1114215 2012-01-01 15:20:35

0

您可以通過轉義反斜槓來將文字\n插入到您的字符串中,例如,

>>> print '\n'; # prints an empty line 

>>> print '\\n'; # prints \n 
\n 

在正則表達式中使用相同的原理。使用此expresion與\n取代所有,中的字符串:

>>> re.sub(",", "\\n", "flurb, durb, hurr") 
'flurb\n durb\n hurr' 
+0

我並沒有問如何逃避\ n我問的是如何用字符串中的'\ n'替換字符','。 – user1114215 2012-01-01 15:21:40

+0

好吧,現在我明白了!謝謝! – user1114215 2012-01-01 15:25:59

+0

對不起,誤解了你的問題。 – bkzland 2012-01-01 15:26:41

2
>>> str = 'Hello, world' 
>>> str = str.replace(',','\n') 
>>> print str 
Hello 
world 

>>> str_list=str.split('\n') 
>>> print str_list 
['Hello', ' world'] 

對於您可以檢查futher操作: http://docs.python.org/library/stdtypes.html

+0

你會如何做一個清單? – user1114215 2012-01-01 15:23:09