2010-10-07 63 views
7

我有一个元组。元组到字符串

tst = ([['name', u'bob-21'], ['name', u'john-28']], True) 

我想将它转换为字符串..

print tst2 
"([['name', u'bob-21'], ['name', u'john-28']], True)" 

什么是做到这一点的好办法?

谢谢!

回答

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

谢谢亚当。我想过使用str,但从来没有想过它会工作! – Dais 2010-10-08 02:35:03

4

虽然我喜欢亚当的建议为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)"