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

SMP*_*288 1 python runtime-error

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

tt = '{}'.format(tt)
Run Code Online (Sandbox Code Playgroud)

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

  hist = '{}'.format(hist)
ValueError: zero length field name in format
Run Code Online (Sandbox Code Playgroud)

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

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

jon*_*rpe 6

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

tt = '{0}'.format(tt)
Run Code Online (Sandbox Code Playgroud)

或者只是使用:

tt = str(tt)
Run Code Online (Sandbox Code Playgroud)

它还将str.format在2.6中引入之前支持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)]'
Run Code Online (Sandbox Code Playgroud)