tags:

views:

101

answers:

6

how to change any data type into a string data in python, and store it as a string variable

+6  A: 
myvariable = 4
mystring = str(myvariable)  # '4'

also, alternatively try repr:

mystring = repr(myvariable) # '4'

This is called "conversion" in python, and is quite common.

orangeoctopus
I wouldn't use repr(myvariable) - it often returns information about class type, memory address etc. It's more useful for debugging. Use str(myvariable) for conversion to string and unicode(variable) for conversion to unicode.
Abgan
Completely agree Abgan, thanks for the elaboration.
orangeoctopus
+1  A: 

With str(x). However, every data type can define its own string conversion, so this might not be what you want.

Philipp
This is an important yet rare consideration. Good that you mentioned it.
jathanism
+1  A: 

str(object) will do the trick.

If you want to alter the way object is stringified, add define __str__(self) method for objects` class. Such method has to return str or unicode object.

Abgan
A: 

Just use str - for example:

>>> str([])
'[]'
Justin Ethier
+4  A: 

Use the str built-in:

x = str(something)

Examples:

>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'

...

From the documentation:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

The MYYN
A: 

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return ...

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return ...

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

Brian S