【问题标题】:Removing a Ton of Leading Spaces and Newline Characters from a String从字符串中删除大量前导空格和换行符
【发布时间】:2013-05-10 14:18:30
【问题描述】:

我有一个 Python 字符串,它在 shell 中打印出以下字符串:

'\\n                autonomy\\n                . . sweeping\\n                \\n            '

如何删除所有这些换行符以及一个或多个空格?

我希望字符串是 'autonomy 。 .扫地”

我试过剥离和替换无济于事。

【问题讨论】:

    标签: python string replace newline


    【解决方案1】:
    fixed_text = " ".join(big_Text_block.split())
    

    这首先在任何空格(包括换行符)上将其分开,第二个使用单个空格作为“胶水”将其重新组合在一起

    【讨论】:

    • 上述失败,因为 '\\n' 不是 python 换行符。请参阅下面适用于@sixglazed 原始字符串的答案。
    • 我不知道这可能只是 repr ,他很清楚地说换行符....print repr("\ntest\n")
    【解决方案2】:

    怎么样:

    >>> txt = '\\n                autonomy\\n                . . sweeping\\n                \\n            '
    >>> newtxt = ' '.join(txt.replace('\\n', ' ').split())
    >>> print (newtxt)
    autonomy . . sweeping
    >>> newtxt
    'autonomy . . sweeping'
    >>> 
    

    【讨论】:

    • 我不确定他的字符串中有\\n ...我怀疑这只是代表...但我可能错了,从 OP 不清楚
    • 不清楚。 (尽管如果它们是换行符,答案会起作用)。
    【解决方案3】:

    你可以使用正则表达式:

    >>> s = '\n                autonomy\n                . . sweeping\n                \n            '
    >>> import re
    >>> re.sub(r'\s\s+', ' ', s).strip()
    'autonomy . . sweeping'
    

    表达式用一个空格替换一个空格字符,后跟一个或多个空格字符。

    【讨论】:

      猜你喜欢
      • 2011-07-25
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多