2014-06-18 140 views
1

我有一個包含元組的列表。我需要將整個列表轉換爲一個字符串進行壓縮。此代碼工作得很好用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版本?

+0

爲什麼不直接使用'STR(TT)'? 'str.format()'很適合將值插入*較大的字符串*;對於一次性字符串轉換,只需使用'str()'。對於單值格式,使用'format()'函數。 –

+3

將Python對象序列化爲原始字符串並不是一個好主意。 [Pickle](https://docs.python.org/2/library/pickle.html)和[json](https://docs.python.org/2/library/json.html)是專門爲此設計的。 – whereswalden

回答

6

放入替換域的索引:

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)]' 
+0

在Python 2.6+中,也可以使用'tt = format(tt)'。 – martineau

相關問題