converting to string

Jeff Shannon jeff at ccvcorp.com
Wed Aug 4 19:48:49 CEST 2004


Ajay wrote:

>hi!
>
>how do i go about converting a Python object or tuple to a string.
>i am currently doing
>import cPickle as pickle
>str = pickle.dumps(obj)
>
>is thate efficient? is that the best way to do it?
>  
>

The "best way to do it" depends very much on what sort of data you're 
trying to convert, and what you intend to do with the string once you 
have it.  (One could argue ;) that the "best way" would require *not* 
using the name 'str' to store your string, since that will mask the name 
of the builtin str() function -- which function might actually do what 
you want, given the extremely vague description of your requirements.)

Pickle is intended to create a serialized version of an object, i.e. one 
that can be saved to disk or sent through a network port and later 
restored to active use.  The fact that this serialized version is a 
string is really just an implementation detail, though it's one that's 
extremely unlikely to change.

If what you really want is a displayable string representation of your 
object/tuple, you might be better off using str() or repr(), possibly 
playing with the object's __str__() or __repr__() methods in order to 
get it to display itself usefully.  These won't necessarily let you 
reconstruct the object from the string, but then you don't list that as 
a requirement.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list