首页 文章

如何从Python字符串中修剪空格?

提问于
浏览
995

如何从Python中的字符串中删除前导和尾随空格?

例如:

" Hello " --> "Hello"
" Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"

7 回答

  • 0

    strip 不限于空格字符:

    # remove all leading/trailing commas, periods and hyphens
    title = title.strip(',.-')
    
  • 108

    你想要strip():

    myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ]
    
    for phrase in myphrases:
        print phrase.strip()
    
  • 238

    没有这个功能,还有一种方法可以做到这一点

    string = "Hello Wor l d "
    tmp_list = []
    for char in string:
        if char != " ":
        tmp_list +=char
    final_string = "".join(tmp_list)
    print final_string
    

    但只是为了好玩:)

  • 45

    只有一个空间,还是所有这样的空间?如果第二个,那么字符串已经有 .strip() 方法:

    >>> ' Hello '.strip()
    'Hello'
    >>> ' Hello'.strip()
    'Hello'
    >>> 'Bob has a cat'.strip()
    'Bob has a cat'
    >>> '          Hello        '.strip()  # ALL spaces at ends removed
    'Hello'
    

    但是,如果您只需删除一个空格,则可以使用以下命令:

    def strip_one_space(s):
        if s.endswith(" "): s = s[:-1]
        if s.startswith(" "): s = s[1:]
        return s
    
    >>> strip_one_space("   Hello ")
    '  Hello'
    

    另请注意, str.strip() 也会删除其他空格字符(例如制表符和换行符) . 要仅删除空格,可以指定要删除的字符作为 strip 的参数,即:

    >>> "  Hello\n".strip(" ")
    'Hello\n'
    
  • -1

    正如上面的答案所指出的那样

    myString.strip()
    

    将删除所有前导和尾随空白字符,例如\ n,\ r,\ t,\ t,\ t \ t \ t,空格 .

    为了更灵活,请使用以下内容

    • 仅删除 leading 空白字符: myString.lstrip()

    • 仅删除 trailing 空格字符: myString.rstrip()

    • 删除 specific 空格字符: myString.strip('\n')myString.lstrip('\n\r')myString.rstrip('\n\t') ,依此类推 .

    更多详情请参阅docs

  • 20

    我想删除字符串中的太多空格(也在字符串之间,不仅在开头或结尾) . 我做了这个,因为我不知道如何做到这一点:

    string = "Name : David         Account: 1234             Another thing: something  " 
    
    ready = False
    while ready == False:
        pos = string.find("  ")
        if pos != -1:
           string = string.replace("  "," ")
        else:
           ready = True
    print(string)
    

    这将替换一个空格中的双空格,直到您不再有双空格为止

  • 1529

    这将删除 myString 中的 all 前导和尾随空格:

    myString.strip()
    

相关问题