我有一个包含数字和字符串的列表:
words = ['hello', 2, 3, 4, 5]
我想要一个字符串:
"'hello', 2, 3, 4, 5"
用 Python 最简单的方法是什么
我有一个包含数字和字符串的列表:
words = ['hello', 2, 3, 4, 5]
我想要一个字符串:
"'hello', 2, 3, 4, 5"
用 Python 最简单的方法是什么
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"
一种使用方式str.strip:
str(words).strip("[]")
输出:
"'hello', 2, 3, 4, 5"
如果我理解你,这是我的解决方案:
单词 = ['你好', 2, 3, 4, 5]
结果 = '''"{}"'''.format(", ".join(map(lambda x: "'{}'".format(str(x)) if isinstance(x, str) else str( x), 单词)))
打印(结果)
输出是:
“‘你好’,2、3、4、5”
做这个:
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