【问题标题】:How to remove double quotes from list of strings?如何从字符串列表中删除双引号?
【发布时间】:2023-04-04 11:39:02
【问题描述】:
VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
    temp = item.replace('"','')
    VERSIONS_F.append(temp)
    print (VERSIONS_F)

在上面的代码块中VERSIONS_F 也打印相同的["'pilot-2'", "'pilot-1'"],但我需要类似['pilot-2', 'pilot-1'] 的东西。我什至尝试了strip('"') 并没有看到我想要的。

【问题讨论】:

    标签: python string list append strip


    【解决方案1】:

    当你打印一个列表时,Python 会打印列表的表示形式,所以列表里面的字符串不会像通常的字符串那样打印出来:

    >>> print('hello')
    hello
    

    相比:

    >>> print(['hello'])
    ['hello']
    

    添加不同的引号会导致Python选择相反的引号来表示字符串:

    >>> print(['\'hello\''])
    ["'hello'"]
    >>> print(["\"hello\""])
    ['"hello"']
    

    Python 初学者经常犯错误,将控制台上打印的内容与实际值混淆。 print(x) 不会向您显示 x 的实际值(无论可能是什么),而是它的文本字符串表示形式。

    例如:

    >>> x = 0xFF
    >>> print(x)
    255
    

    这里,一个值被分配为其十六进制表示,但当然实际值只是 255(十进制表示),十进制表示是打印整数值时选择的标准表示。

    变量的“真实”值是一个抽象数值,表示它时所做的选择不会影响它。

    在您的情况下,您使用VERSION = ["'pilot-2'", "'pilot-1'"] 将字符串定义为将单引号作为字符串的一部分。所以,如果你想删除那些单引号,你可以:

    VERSION = ["'pilot-2'", "'pilot-1'"]
    VERSIONS_F = []
    for item in VERSION:
        temp = item.replace("'",'')
        VERSIONS_F.append(temp)
        print (VERSIONS_F)
    

    结果:

    ['pilot-2']
    ['pilot-2', 'pilot-1']
    

    或者,更简单地说:

    VERSIONS_F = [v.strip("'") for v in VERSION]
    

    回应评论:

    VERSION = ["'pilot-2'", "'pilot-1'"]
    temp_list = ['pilot-1', 'test-3']
    
    print(any(x in [v.strip("'") for v in VERSION] for x in temp_list))
    

    【讨论】:

    • 谢谢你的回答,但是说我想比较/查找另一个列表 temp_list = ['pilot-1'] 的元素是否在上面的列表 VERSION 中。理想情况下它应该返回 true,但我没有看到它发生。有什么比较好的方法?
    【解决方案2】:

    您可以用几行代码完成此操作:

    VERSION = ["'pilot-2'", "'pilot-1'"]
    VERSIONS_F = [item [1:-1] for item in VERSION]
    print(VERSIONS_F)
    

    输出:

    ['pilot-2', 'pilot-1']
    

    这种方式只是从字符串中切出第一个和最后一个字符,假设“”总是在第一个和最后一个位置。

    注意:Grismar 也很好地概述了幕后发生的事情

    【讨论】:

      【解决方案3】:

      试试这个:

      VERSION = ["'pilot-2'", "'pilot-1'"]
      VERSIONS_F = []
      for item in VERSION:
        temp = item.replace("'",'')
        VERSIONS_F.append(temp)
      print (VERSIONS_F)
      

      它将打印 ['pilot-2','pilot-1']

      【讨论】:

        猜你喜欢
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        相关资源
        最近更新 更多