首页 文章

我如何修剪空白?

提问于
浏览
940

是否有一个Python函数可以从字符串中修剪空格(空格和制表符)?

示例: \t example string\texample string

14 回答

  • 18

    这将从字符串的开头和结尾删除所有空格和换行符:

    >>> s = "  \n\t  \n   some \n text \n     "
    >>> re.sub("^\s+|\s+$", "", s)
    >>> "some \n text"
    
  • 1420

    双方空白:

    s = "  \t a string example\t  "
    s = s.strip()
    

    右侧的空白:

    s = s.rstrip()
    

    左侧的空白:

    s = s.lstrip()
    

    正如thedz指出的那样,你可以提供一个参数来将任意字符剥离到这些函数中,如下所示:

    s = s.strip(' \t\n\r')
    

    这将从字符串的左侧,右侧或两侧剥离任何空格, \t\n\r 字符 .

    上面的示例仅从字符串的左侧和右侧删除字符串 . 如果您还要从字符串中间删除字符,请尝试 re.sub

    import re
    print re.sub('[\s+]', '', s)
    

    那应该打印出来:

    astringexample
    
  • 4

    Python trim 方法称为 strip

    str.strip() #trim
    str.lstrip() #ltrim
    str.rstrip() #rtrim
    
  • -17

    对于前导和尾随空格:

    s = '   foo    \t   '
    print s.strip() # prints "foo"
    

    否则,正则表达式起作用:

    import re
    pat = re.compile(r'\s+')
    s = '  \t  foo   \t   bar \t  '
    print pat.sub('', s) # prints "foobar"
    
  • 3

    您还可以使用非常简单的基本函数:str.replace(),使用空格和制表符:

    >>> whitespaces = "   abcd ef gh ijkl       "
    >>> tabs = "        abcde       fgh        ijkl"
    
    >>> print whitespaces.replace(" ", "")
    abcdefghijkl
    >>> print tabs.replace(" ", "")
    abcdefghijkl
    

    简单易行 .

  • 59
    #how to trim a multi line string or a file
    
    s=""" line one
    \tline two\t
    line three """
    
    #line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
    
    s1=s.splitlines()
    print s1
    [' line one', '\tline two\t', 'line three ']
    
    print [i.strip() for i in s1]
    ['line one', 'line two', 'line three']
    
    
    
    
    #more details:
    
    #we could also have used a forloop from the begining:
    for line in s.splitlines():
        line=line.strip()
        process(line)
    
    #we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
    for line in my_file:
        line=line.strip()
        process(line)
    
    #moot point: note splitlines() removed the newline characters, we can keep them by passing True:
    #although split() will then remove them anyway..
    s2=s.splitlines(True)
    print s2
    [' line one\n', '\tline two\t\n', 'line three ']
    
  • -1

    还没有人发布这些正则表达式解决方案 .

    匹配:

    >>> import re
    >>> p=re.compile('\\s*(.*\\S)?\\s*')
    
    >>> m=p.match('  \t blah ')
    >>> m.group(1)
    'blah'
    
    >>> m=p.match('  \tbl ah  \t ')
    >>> m.group(1)
    'bl ah'
    
    >>> m=p.match('  \t  ')
    >>> print m.group(1)
    None
    

    搜索(您必须以不同方式处理“仅空格”输入大小写):

    >>> p1=re.compile('\\S.*\\S')
    
    >>> m=p1.search('  \tblah  \t ')
    >>> m.group()
    'blah'
    
    >>> m=p1.search('  \tbl ah  \t ')
    >>> m.group()
    'bl ah'
    
    >>> m=p1.search('  \t  ')
    >>> m.group()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'group'
    

    如果使用 re.sub ,则可能会删除内部空格,这可能是不合需要的 .

  • 0

    空白包括 space, tabs and CRLF . 所以我们可以使用的优雅和 one-liner 字符串函数是 translate .

    ' hello apple'.translate(None, ' \n\t\r')

    OR 如果你想要彻底

    import string
    ' hello  apple'.translate(None, string.whitespace)
    
  • 2
    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "
    
        something = "".join(something.split())
    

    输出:please_remove_all_whitespaces

  • 0

    (re.sub('','',(my_str.replace('\ n','')))) . strip()

    这将删除所有不需要的空格和换行符 . 希望这有帮助

    import re
    my_str = '   a     b \n c   '
    formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()
    

    这将导致:

    ' a b \n c ' 将更改为 'a b c'

  • 2

    尝试翻译

    >>> import string
    >>> print '\t\r\n  hello \r\n world \t\r\n'
    
      hello 
     world  
    >>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
    >>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr)
    '     hello    world    '
    >>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
    'helloworld'
    
  • 12

    如果使用Python 3:在print语句中,请使用sep =“”结束 . 这将分离出所有空间 .

    例:

    txt="potatoes"
    print("I love ",txt,"",sep="")
    

    This will print: 我喜欢土 beans .

    Instead of: 我喜欢土 beans .

    在你的情况下,因为你试图乘坐\ t,所以做sep =“\ t”

  • 21

    一般来说,我使用以下方法:

    >>> myStr = "Hi\n Stack Over \r flow!"
    >>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
    >>> import re
    >>> for i in charList:
            myStr = re.sub(i, r"", myStr)
    
    >>> myStr
    'Hi Stack Over  flow'
    

    注意:这仅用于删除“\ n”,“\ r”和“\ t” . 它不会删除多余的空格 .

  • -2

    用于从字符串中间删除空格

    $p = "ATGCGAC ACGATCGACC";
    $p =~ s/\s//g;
    print $p;
    

    输出:ATGCGACACGATCGACC

相关问题