Python和换行符

时间:2012-01-01 15:12:53

标签: python string python-2.7

使用Python我知道“\ n”打破了字符串中的下一行,但我想要做的是用'\ n'替换字符串中的每个“,”。那可能吗?我是Python的新手。

3 个答案:

答案 0 :(得分:3)

试试这个:

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

列表:

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

答案 1 :(得分:2)

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

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

如需进一步操作,您可以查看:http://docs.python.org/library/stdtypes.html

答案 2 :(得分:0)

您可以通过转义反斜杠将字面值\n插入到字符串中,例如

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

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

在正则表达式中使用相同的原则。使用此表达式将字符串中的所有,替换为\n

>>> re.sub(",", "\\n", "flurb, durb, hurr")
'flurb\n durb\n hurr'
相关问题