0

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

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

我想要一个字符串:

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

用 Python 最简单的方法是什么

4

4 回答 4

3
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"
于 2020-07-10T05:39:04.413 回答
2

一种使用方式str.strip

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

输出:

"'hello', 2, 3, 4, 5"
于 2020-07-10T06:10:54.910 回答
0

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

单词 = ['你好', 2, 3, 4, 5]

结果 = '''"{}"'''.format(", ".join(map(lambda x: "'{}'".format(str(x)) if isinstance(x, str) else str( x), 单词)))

打印(结果)

输出是:

“‘你好’,2、3、4、5”
于 2020-07-10T05:56:07.110 回答
-1

做这个:

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
于 2020-07-10T05:38:19.290 回答