【问题标题】:Python and Line BreaksPython 和换行符
【发布时间】:2012-01-31 09:34:01
【问题描述】:

使用 Python,我知道“\n”会中断到字符串中的下一行,但我想做的是用“\n”替换字符串中的每个“,”。那可能吗?我对 Python 有点陌生。

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    试试这个:

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

    对于列表:

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

    【讨论】:

    • 不客气 :) 如果答案有用,请考虑接受它
    • 我正在尝试排除它,但网站一直给我一个错误,告诉我我必须等待 5 分钟才能排除它。
    【解决方案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

    【讨论】:

    • 您将如何处理列表?
    【解决方案3】:

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

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

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

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

    【讨论】:

    • 我不是在问如何转义 \n 我是在问如何将字符串中的字符 ',' 替换为 '\n'。
    猜你喜欢
    • 2012-09-24
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多