【问题标题】:How do I trim whitespace from a string?如何从字符串中修剪空格?
【发布时间】:2010-10-20 04:40:08
【问题描述】:

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

例如:

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

【问题讨论】:

  • 只是为了让更多人知道rstrip的陷阱。 'WKHS.US.TXT'.rstrip('.US.TXT') 将返回 WKH 而不是 WKHS。这个rstrip 造成了一个我很难解决的BUG。

标签: python string trim


【解决方案1】:

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

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both 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'

【讨论】:

  • 如果需要strip函数,比如map函数,可以通过str.strip()来访问,比如map(str.strip, collection_of_s)
  • 有没有办法只修剪末尾的空格?
  • @killthrush 感谢您的参考,但我认为您的意思是 rstrip() 函数。 :-)
  • 有时我觉得python故意避免使用绝大多数语言为了“独特”和“不同”而使用的广为接受且有意义的名称——strip而不是trimisinstance而不是instanceoflist而不是array等等等等。为什么不直接用大家都熟悉的名字呢??天哪:P
  • @GershomMaes 在strip 的情况下,我完全同意,但列表与数组完全不同。
【解决方案2】:

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

my_string.strip()

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

为了获得更大的灵活性,请使用以下

  • 仅删除 前导 空白字符:my_string.lstrip()
  • 仅删除 尾随 空白字符:my_string.rstrip()
  • 删除特定空白字符:my_string.strip('\n')my_string.lstrip('\n\r')my_string.rstrip('\n\t') 等等。

更多详情,请访问docs

【讨论】:

  • 我认为是 \r\n 不是 \n\r ...(无法编辑帖子 - 修改的字符数不足)
  • @StefanNch:字符的顺序根本不重要。 \n\r 也会删除 \r\n。
【解决方案3】:

strip 也不限于空白字符:

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

【讨论】:

    【解决方案4】:

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

    myString.strip()
    

    【讨论】:

      【解决方案5】:

      你想要strip():

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

      【讨论】:

      • print([phrases.strip() for phrase in myphrases ])
      【解决方案6】:

      这也可以用正则表达式来完成

      import re
      
      input  = " Hello "
      output = re.sub(r'^\s+|\s+$', '', input)
      # output = 'Hello'
      

      【讨论】:

        【解决方案7】:

        作为一个初学者看到这个线程让我头晕目眩。因此想出了一个简单的捷径。

        虽然 str.strip() 可以删除前导空格和尾随空格,但它对字符之间的空格没有任何作用。

        words=input("Enter the word to test")
        # If I have a user enter discontinous threads it becomes a problem
        # input = "   he llo, ho w are y ou  "
        n=words.strip()
        print(n)
        # output "he llo, ho w are y ou" - only leading & trailing spaces are removed 
        

        改为使用 str.replace() 更有意义,错误更少,更切中要害。 下面的代码可以概括str.replace()的使用

        def whitespace(words):
            r=words.replace(' ','') # removes all whitespace
            n=r.replace(',','|') # other uses of replace
            return n
        def run():
            words=input("Enter the word to test") # take user input
            m=whitespace(words) #encase the def in run() to imporve usability on various functions
            o=m.count('f') # for testing
            return m,o
        print(run())
        output- ('hello|howareyou', 0)
        

        在 diff 中继承相同的内容时可能会有所帮助。功能。

        【讨论】:

          【解决方案8】:

          为了删除在 Pyhton 中运行完成的代码或程序时会导致大量缩进错误的“空白”。只需执行以下操作;显然,如果 Python 一直提示错误是第 1、2、3、4、5 行等中的缩进,则只需来回修复该行。

          但是,如果您仍然遇到与输入错误、运算符等有关的程序问题,请确保您阅读了 Python 对您大喊大叫的原因:

          首先要检查的是你有你的 缩进正确。如果有,请检查是否有 代码中带有空格的混合制表符。

          记住:代码 看起来不错(对你来说),但解释器拒绝运行它。如果 您怀疑这一点,快速解决方法是将您的代码放入 IDLE 编辑窗口,然后选择 Edit..."Select All 从 菜单系统,在选择 Format..."Untabify Region 之前。 如果您将制表符与空格混合在一起,这将转换您的所有 一次将制表符转换为空格(并修复任何缩进问题)。

          【讨论】:

            【解决方案9】:

            我找不到我正在寻找的解决方案,所以我创建了一些自定义函数。你可以试试看。

            def cleansed(s: str):
                """:param s: String to be cleansed"""
                assert s is not (None or "")
                # return trimmed(s.replace('"', '').replace("'", ""))
                return trimmed(s)
            
            
            def trimmed(s: str):
                """:param s: String to be cleansed"""
                assert s is not (None or "")
                ss = trim_start_and_end(s).replace('  ', ' ')
                while '  ' in ss:
                    ss = ss.replace('  ', ' ')
                return ss
            
            
            def trim_start_and_end(s: str):
                """:param s: String to be cleansed"""
                assert s is not (None or "")
                return trim_start(trim_end(s))
            
            
            def trim_start(s: str):
                """:param s: String to be cleansed"""
                assert s is not (None or "")
                chars = []
                for c in s:
                    if c is not ' ' or len(chars) > 0:
                        chars.append(c)
                return "".join(chars).lower()
            
            
            def trim_end(s: str):
                """:param s: String to be cleansed"""
                assert s is not (None or "")
                chars = []
                for c in reversed(s):
                    if c is not ' ' or len(chars) > 0:
                        chars.append(c)
                return "".join(reversed(chars)).lower()
            
            
            s1 = '  b Beer '
            s2 = 'Beer  b    '
            s3 = '      Beer  b    '
            s4 = '  bread butter    Beer  b    '
            
            cdd = trim_start(s1)
            cddd = trim_end(s2)
            clean1 = cleansed(s3)
            clean2 = cleansed(s4)
            
            print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
            print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
            print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
            print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
            

            【讨论】:

              【解决方案10】:

              如果您想从左右修剪指定数量的空格,您可以这样做:

              def remove_outer_spaces(text, num_of_leading, num_of_trailing):
                  text = list(text)
                  for i in range(num_of_leading):
                      if text[i] == " ":
                          text[i] = ""
                      else:
                          break
              
                  for i in range(1, num_of_trailing+1):
                      if text[-i] == " ":
                          text[-i] = ""
                      else:
                          break
                  return ''.join(text)
              
              txt1 = "   MY name is     "
              print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
              print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
              print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"
              

              【讨论】:

                【解决方案11】:

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

                所以下面的解决方案也将删除前导和尾随空格以及中间空格。就像您需要获得没有多个空格的清晰字符串值一样。

                >>> str_1 = '     Hello World'
                >>> print(' '.join(str_1.split()))
                Hello World
                >>>
                >>>
                >>> str_2 = '     Hello      World'
                >>> print(' '.join(str_2.split()))
                Hello World
                >>>
                >>>
                >>> str_3 = 'Hello World     '
                >>> print(' '.join(str_3.split()))
                Hello World
                >>>
                >>>
                >>> str_4 = 'Hello      World     '
                >>> print(' '.join(str_4.split()))
                Hello World
                >>>
                >>>
                >>> str_5 = '     Hello World     '
                >>> print(' '.join(str_5.split()))
                Hello World
                >>>
                >>>
                >>> str_6 = '     Hello      World     '
                >>> print(' '.join(str_6.split()))
                Hello World
                >>>
                >>>
                >>> str_7 = 'Hello World'
                >>> print(' '.join(str_7.split()))
                Hello World
                

                如您所见,这将删除字符串中的所有多个空格(全部输出为Hello World)。位置无所谓。但是,如果您确实需要前导和尾随空格,则可以找到 strip()

                【讨论】:

                  【解决方案12】:

                  我想删除字符串中过多的空格(也在字符串之间,不仅在开头或结尾)。我做了这个,因为我不知道该怎么做:

                  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)
                  

                  这会替换一个空格中的双空格,直到你不再有双空格

                  【讨论】:

                  • 虽然这样有效,但效率不高,改用这个:stackoverflow.com/a/2077906/1240286
                  • 如果你想删除所有空格只需使用 string.replace(" ","") 不需要所有这些代码
                  猜你喜欢
                  • 2010-09-16
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-05-20
                  • 1970-01-01
                  • 2016-01-21
                  相关资源
                  最近更新 更多