【问题标题】:Remove white spaces from the beginning of each string in a list [duplicate]从列表中每个字符串的开头删除空格[重复]
【发布时间】:2022-01-03 03:10:23
【问题描述】:

如何删除列表中每个字符串开头的空格?

List = [' a', ' b', ' c']

这是我尝试过的,但列表保持不变:

unique_items_1 = []

for i in unique_items:
    j = i.replace('^ +', '')
    unique_items_1.append(j)

print(List)

我的预期结果是:

List = ['a', 'b', 'c']

【问题讨论】:

    标签: python for-loop arraylist removing-whitespace


    【解决方案1】:

    在列表理解中使用str.lstrip

    my_list = [' a', ' b', ' c']
    
    my_list = [i.lstrip() for i in my_list]
    print(my_list)  # ['a', 'b', 'c']
    

    【讨论】:

      【解决方案2】:

      要删除前导空格,您可以使用lstrip 函数。 就您而言,对于列表:

      result = [x.lstrip() for x in List]
      print(result)
      

      去除尾随空格:

      result = [x.rstrip() for x in List]
      print(result)
      

      以下代码通常可以删除所有空格:

      result = [x.replace(' ','') for x in List
      print(result)
      

      【讨论】:

        【解决方案3】:
        List = [' a',' b',' c']
        
        print(List) # [' a', ' b', ' c']
        
        List_Trimmed = [*map(lambda x: x.lstrip(), List)]
        
        print(List_Trimmed) # ['a', 'b', 'c']
        

        【讨论】:

          【解决方案4】:

          你可以使用strip():

          for i in unique_items:
             j = i.strip()
             unique_items_1.append(j)
          

          strip() 删除空格。

          您也可以使用lstrip()

          【讨论】:

            猜你喜欢
            • 2021-03-07
            • 1970-01-01
            • 2011-04-08
            • 1970-01-01
            • 2013-04-14
            • 2017-12-12
            • 2016-09-30
            • 2011-12-22
            • 1970-01-01
            相关资源
            最近更新 更多