Skip to main content
 首页 » 编程设计

python之将包含元组的列表转换为字符串

2025年05月04日24lautakyan007

我有一个包含元组的列表。我需要将整个列表转换为字符串以进行压缩。此代码在 Python 2.7 中运行良好:

tt = '{}'.format(tt) 

但在 Python 2.6 中我得到以下错误:

  hist = '{}'.format(hist) 
ValueError: zero length field name in format 

tt 中的数据看起来像[(2, 3, 4), (34, 5, 7)...]

除了升级 Python 版本之外,还有什么解决方法吗?

请您参考如下方法:

在替换字段中放置一个索引:

tt = '{0}'.format(tt) 

或者只是使用:

tt = str(tt) 

这也将支持在 2.6 中引入 str.format 之前的 Python 版本。

演示:

>>> tt = [(2, 3, 4), (34, 5, 7)] 
>>> "{0}".format(tt) 
'[(2, 3, 4), (34, 5, 7)]' 
>>> str(tt) 
'[(2, 3, 4), (34, 5, 7)]'