【发布时间】:2012-01-31 09:34:01
【问题描述】:
使用 Python,我知道“\n”会中断到字符串中的下一行,但我想做的是用“\n”替换字符串中的每个“,”。那可能吗?我对 Python 有点陌生。
【问题讨论】:
标签: python string python-2.7
使用 Python,我知道“\n”会中断到字符串中的下一行,但我想做的是用“\n”替换字符串中的每个“,”。那可能吗?我对 Python 有点陌生。
【问题讨论】:
标签: python string python-2.7
试试这个:
text = 'a, b, c'
text = text.replace(',', '\n')
print text
对于列表:
text = ['a', 'b', 'c']
text = '\n'.join(text)
print text
【讨论】:
>>> str = 'Hello, world'
>>> str = str.replace(',','\n')
>>> print str
Hello
world
>>> str_list=str.split('\n')
>>> print str_list
['Hello', ' world']
【讨论】:
您可以通过转义反斜杠将文字 \n 插入到您的字符串中,例如
>>> print '\n'; # prints an empty line
>>> print '\\n'; # prints \n
\n
在正则表达式中使用相同的原理。使用此表达式将字符串中的所有, 替换为\n:
>>> re.sub(",", "\\n", "flurb, durb, hurr")
'flurb\n durb\n hurr'
【讨论】: