how to change any data type into a string in python
How can I change any data type into a string in Python?
Solution 1:
myvariable = 4
mystring = str(myvariable) # '4'
also, alternatively try repr:
mystring = repr(myvariable) # '4'
This is called "conversion" in python, and is quite common.
Solution 2:
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 "Some descriptive string"
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 "Some descriptive string"
>>> myObj
in your interactions pane, or repr(myObj)
, will result in myObj.__repr__()