【问题标题】:Strip spaces/tabs/newlines - python去除空格/制表符/换行符 - python
【发布时间】:2012-05-29 11:31:39
【问题描述】:

我正在尝试在 Linux 上删除 python 2.7 中的所有空格/制表符/换行符。

我写了这个,应该做的工作:

myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = myString.strip(' \n\t')
print myString

输出:

I want to Remove all white   spaces, new lines 
 and tabs

这似乎是一件简单的事情,但我在这里缺少一些东西。我应该导入一些东西吗?

【问题讨论】:

标签: python string python-2.7 strip


【解决方案1】:

在连接中使用列表推导式的单行如何?

>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb                 ccc
ddd

>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd

【讨论】:

    【解决方案2】:

    因为没有比这更复杂的了,我想分享这个,因为它帮助了我。

    这是我最初使用的:

    import requests
    import re
    
    url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
    headers = {'user-agent': 'my-app/0.0.1'}
    r = requests.get(url, headers=headers)
    print("{}".format(r.content))
    

    不想要的结果:

    b'<!DOCTYPE html>\r\n\r\n\r\n    <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">\r\n\r\n    <head>\r\n\r\n        <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>\r\n        <link
    

    这是我改成的:

    import requests
    import re
    
    url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
    headers = {'user-agent': 'my-app/0.0.1'}
    r = requests.get(url, headers=headers)
    regex = r'\s+'
    print("CNT: {}".format(re.sub(regex, " ", r.content.decode('utf-8'))))
    

    期望的结果:

    <!DOCTYPE html> <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive"> <head> <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>
    

    @MattH 提到的精确正则表达式对我来说很有效,可以将它融入我的代码中。谢谢!

    注意:这是python3

    【讨论】:

      【解决方案3】:

      上述建议使用正则表达式的解决方案并不理想,因为这是一项非常小的任务,而且正则表达式需要的资源开销比任务的简单性所证明的要多。

      这是我的工作:

      myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')

      或者如果你有一堆东西要删除,这样单行解决方案就会无缘无故地冗长:

      removal_list = [' ', '\t', '\n']
      for s in removal_list:
        myString = myString.replace(s, '')
      

      【讨论】:

        【解决方案4】:

        这只会删除制表符、换行符、空格等。

        import re
        myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
        output   = re.sub(r"[\n\t\s]*", "", myString)
        

        输出:

        我想删除所有空格、换行符和制表符

        美好的一天!

        【讨论】:

        • 感谢您的解决方案 - 我认为需要进行小修正,应该是 '+' 而不是 '*'。
        【解决方案5】:

        使用 re

        import re
        myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
        myString = re.sub(r"[\n\t\s]*", "", myString)
        print myString
        

        输出:

        我想删除所有空格、换行符和制表符

        【讨论】:

        • 这是对@TheGr8Adakron 给出的原始答案的更正,不是重复的
        【解决方案6】:

        使用str.split([sep[, maxsplit]]),不使用sepsep=None

        来自docs

        如果sep没有被指定或者是None,一个不同的分割算法是 应用:连续空白的运行被视为单个 分隔符,结果开头不包含空字符串 如果字符串有前导或尾随空格,则结束。

        演示:

        >>> myString.split()
        ['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']
        

        在返回的列表上使用str.join 来获得这个输出:

        >>> ' '.join(myString.split())
        'I want to Remove all white spaces, new lines and tabs'
        

        【讨论】:

          【解决方案7】:
          import re
          
          mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
          print re.sub(r"\W", "", mystr)
          
          Output : IwanttoRemoveallwhitespacesnewlinesandtabs
          

          【讨论】:

          • 这也删除了';'
          【解决方案8】:

          如果您想删除多个空白项并用单个空格替换它们,最简单的方法是使用这样的正则表达式:

          >>> import re
          >>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
          >>> re.sub('\s+',' ',myString)
          'I want to Remove all white spaces, new lines and tabs '
          

          如果需要,您可以使用.strip() 删除尾随空格。

          【讨论】:

            猜你喜欢
            • 2014-10-04
            • 1970-01-01
            • 2018-06-14
            • 2015-12-12
            • 2017-09-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多