Python and Line Breaks



使用Python,我知道"n"会中断到字符串中的下一行,但我要做的是将字符串中的每个","替换为'n'。这可能吗?我对Python有点陌生

试试这个:

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']

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

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

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

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

>>> re.sub(",", "\n", "flurb, durb, hurr")
'flurbn durbn hurr'

最新更新