Python and Line Breaks

前端 未结 3 647
鱼传尺愫
鱼传尺愫 2021-01-21 20:07

With Python I know that the \"\\n\" breaks to the next line in a string, but what I am trying to do is replace every \",\" in a string with a \'\\n\'. Is that possible? I am kin

相关标签:
3条回答
  • 2021-01-21 20:41
    >>> str = 'Hello, world'  
    >>> str = str.replace(',','\n')  
    >>> print str  
    Hello  
     world
    
    >>> str_list=str.split('\n')
    >>> print str_list
    ['Hello', ' world']
    

    For futher operations you may check: http://docs.python.org/library/stdtypes.html

    0 讨论(0)
  • 2021-01-21 20:48

    Try this:

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

    For lists:

    text = ['a', 'b', 'c']
    text = '\n'.join(text)
    print text
    
    0 讨论(0)
  • 2021-01-21 20:52

    You can insert a literal \n into your string by escaping the backslash, e.g.

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

    The same principle is used in regular expressions. Use this expresion to replace all , in a string with \n:

    >>> re.sub(",", "\\n", "flurb, durb, hurr")
    'flurb\n durb\n hurr'
    
    0 讨论(0)
提交回复
热议问题