【问题标题】:Join a list of strings and number in python and wrap each string in quotation marks加入python中的字符串和数字列表并将每个字符串用引号引起来
【发布时间】:2020-07-10 05:32:55
【问题描述】:

我有一个包含数字和字符串的列表:

words = ['hello', 2, 3, 4, 5]

我想要一个字符串:

"'hello', 2, 3, 4, 5"

用 Python 最简单的方法是什么

【问题讨论】:

  • 这能回答你的问题吗? printing double quotes around a variable
  • 如果存在另一个字符串,您希望发生什么?例如words = ['hello', 2, 3, 'there', 5]?如果words = [1, 2, 'hello', 4, 5] 转换任何字符串或仅转换第一个元素怎么办?
  • words = ['hello', 2, 3, 'there', 5] 这也是可能的 或者words = ['hello',' 2', '3', '4', '5'] 在这一个中,我必须更改第一个不是数字的。

标签: python-3.x string list


【解决方案1】:
words = ['hello', 2, 3, 4, 5]
", ".join([str(x) if isinstance(x,int) else "'{}'".format(x) for x in words])

输出:

"'hello', 2, 3, 4, 5"

【讨论】:

    【解决方案2】:

    一种使用str.strip的方式:

    str(words).strip("[]")
    

    输出:

    "'hello', 2, 3, 4, 5"
    

    【讨论】:

    • 一个不错的技巧。感谢这个答案
    【解决方案3】:

    如果我理解你,这就是我的解决方案:

    单词 = ['你好', 2, 3, 4, 5] 结果 = '''"{}"'''.format(", ".join(map(lambda x: "'{}'".format(str(x)) if isinstance(x, str) else str( x), 单词))) 打印(结果)

    输出是:

    “‘你好’,2、3、4、5”

    【讨论】:

      【解决方案4】:

      这样做:

      words = ['hello', 2, 3, 4, 5]
      print(','.join([str(elem) if isinstance(elem,int) else "'{}'".format(elem) for elem in words]) )
      

      输出:

      'hello',2,3,4,5
      

      【讨论】:

      • 预期输出不同
      • 它没有 `` 表示你好这个词。你的很完美
      猜你喜欢
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多