【问题标题】:How to delete spaces in printing the list?如何删除打印列表中的空格?
【发布时间】:2020-11-16 10:20:08
【问题描述】:
def lexemize_Ari_Exp():
    
    arithmeticExpression = input("Write an Arithmetic Expression: ")
    list_Of_Arit_Exp = []
  
    for x in arithmeticExpression:
        list_Of_Arit_Exp.append(x)
    print(list_Of_Arit_Exp)
        
lexemize_Ari_Exp()

#输入:x + 1

#输出:['x','','+','','1']

【问题讨论】:

  • 您要查找的输出到底是什么?
  • 只需在输入的末尾添加 .split() 函数并删除其余部分。

标签: python python-3.x list loops input


【解决方案1】:

如果表达式的每个元素都用空格分隔,您可以简单地使用split() 函数:

def lexemize_Ari_Exp():
    
    arithmeticExpression = input("Write an Arithmetic Expression: ")
    list_Of_Arit_Exp = arithmeticExpression.split()
    
    print(list_Of_Arit_Exp)
        
lexemize_Ari_Exp()

输出示例:

Write an Arithmetic Expression: x + 1
['x', '+', '1']

【讨论】:

    【解决方案2】:

    您可以像这样简单地添加一个 if 语句:

    for x in arithmeticExpression:
        if not x == ' ':
            list_Of_Arit_Exp.append(x)
    

    这是因为你的 for 循环迭代输入字符串的每一个字符,而 x 只代表每次迭代中的字符。

    【讨论】:

      【解决方案3】:
      def remove (list, toRemove):
           for i in range (0, list.count (toRemove)):
               list.pop (list.index (toRemove))
           return list
      

      使用此功能从列表中删除您想要的元素

      list = [0, 1, 0]
      print (remove (list, 0))#Remove all the 0 from the list
      

      适用于所有类型(int、float、string...)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 2014-05-26
        • 2014-12-14
        • 1970-01-01
        • 2018-11-20
        • 1970-01-01
        • 2017-03-05
        相关资源
        最近更新 更多