Dais
Dais

Reputation: 93

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']], True)"

what is a good way to do this?

Thanks!

Upvotes: 9

Views: 26826

Answers (2)

Stigma
Stigma

Reputation: 1736

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

Upvotes: 4

mechanical_meat
mechanical_meat

Reputation: 169304

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

Upvotes: 18

Related Questions