7
我有一個元組。元組到字符串
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
我想將它轉換爲字符串..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
什麼是做到這一點的好辦法?
謝謝!
我有一個元組。元組到字符串
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
我想將它轉換爲字符串..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
什麼是做到這一點的好辦法?
謝謝!
tst2 = str(tst)
如:
>>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
>>> tst2 = str(tst)
>>> print tst2
([['name', u'bob-21'], ['name', u'john-28']], True)
>>> repr(tst2)
'"([[\'name\', u\'bob-21\'], [\'name\', u\'john-28\']], True)"'
雖然我喜歡亞當的建議爲str()
,我會向repr()
傾斜相反,鑑於你是明確尋找的一個Python語法般的表現目的。如果判斷help(str)
,則其元組的字符串轉換可能在未來的版本中以不同方式定義。
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
...
與之相對help(repr)
:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
在今天的實踐和環境雖然有會是二者相差不大,所以用什麼描述您的最佳的需要 - 東西,你可以反饋給eval()
,或用於用戶消費的東西。
>>> str(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
>>> repr(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
謝謝亞當。我想過使用str,但從來沒有想過它會工作! – Dais 2010-10-08 02:35:03