Skip to main content
 首页 » 编程设计

python之加入混合类型的列表,引号只包含在字符串周围

2025年05月04日21kenshinobiy

我有一个包含混合对象类型(字符串和整数)的列表,我想做的是将该列表连接到一个字符串中,其中每个字符串都用引号引起来,除了整数。例如,如果我有这个列表:

sample_list = ['abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar'] 

我想从中生成以下字符串:

sample_string = "('abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar')" 

这是我的:

sample_string = "(" + ', '.join("'{0}'".format(item) for item in sample_list if type(item) is not int) + ")" 

显然我的代码是错误的,因为我的整数值最终由于 'if' 语句而被丢弃,但我一直在寻找一种优雅的方式来生成我想要的字符串,并且想知道是否有人可以提供一些有关如何这样做的提示。

提前致谢!

请您参考如下方法:

怎么样:

str(tuple(sample_list)) 

返回:

"('abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar')"