开发者

Tuple to string

I have a tuple.

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

And I want to convert it to a string..

print tst2
"([['name', u'bob-21'], ['name', u'john-28']], T开发者_StackOverflow社区rue)"

what is a good way to do this?

Thanks!


tst2 = str(tst)

E.g.:

>>> 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)"'


While I like Adam's suggestion for str(), I'd be leaning towards repr() instead, given the fact you are explicitly looking for a python-syntax-like representation of the object. Judging help(str), its string conversion for a tuple might end up defined differently in future versions.

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.
 ...

As opposed to help(repr):

repr(...)
    repr(object) -> string

    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

In todays practice and environment though, there'd be little difference between the two, so use what describes your need best - something you can feed back to eval(), or something meant for user consumption.

>>> str(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
>>> repr(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜