元组转字符串
我有一个元组。
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
我想把它转换成一个字符串。
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
有什么好的方法可以做到这一点吗?
谢谢!
2 个回答
4
我很喜欢Adam对str()
的建议,但考虑到你明确想要一个像Python语法那样的对象表示,我更倾向于使用repr()
。根据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)"
18
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)"'
例如: