165

How can I change any data type into a string in Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
duhhunjonn
  • 44,855
  • 11
  • 28
  • 15

10 Answers10

147
myvariable = 4
mystring = str(myvariable)  # '4'

also, alternatively try repr:

mystring = repr(myvariable) # '4'

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

Donald Miner
  • 38,889
  • 8
  • 95
  • 118
  • 6
    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 Jul 08 '10 at 14:29
  • 5
    What about unicode? Something like `str(u'ä')` will not work. However `repr(u'ä')` will work. – Robsdedude Oct 10 '16 at 09:23
  • 2
    what about None and False? – fredless Jun 19 '19 at 15:55
  • 1
    does every class/type in python always allows `str` to be called on it without error? – Charlie Parker Oct 25 '20 at 16:24
72

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__()

Drise
  • 4,310
  • 5
  • 41
  • 66
Brian S
  • 4,878
  • 4
  • 27
  • 46
  • It's probably true that the majority of core library objects by raw percentage return the `object.__repr__`-style angle-bracket representation, but many of the most commonly used ones do not. The rule of thumb for `repr` is that if it makes sense to return Python code that could be evaluated to produce the same object, do that, just like `str`, `frozenset`, and most other builtins do, but if it doesn't, use the angle-bracket form to make sure that what you return can't possibly be mistaken for a human-readable-and-evaluatable-as-source repr. – abarnert Mar 21 '18 at 17:09
  • (Of course some of the builtins violate that rule of thumb—a `list` that includes itself returns something that not only looks like but is evaluable code, which evaluates to the wrong thing—but the core devs have never taken that as license to expand the same behavior into the stdlib.) – abarnert Mar 21 '18 at 17:10
  • does every class/type in python always allows `str` to be called on it without error? – Charlie Parker Oct 25 '20 at 16:24
  • @CharlieParker yes; `__str__` is a function inherited from the object class, which is the root for all other classes in Python. https://docs.python.org/3/reference/datamodel.html#object.__str__ – Brian S Nov 05 '20 at 08:56
21

I see all answers recommend using str(object). It might fail if your object have more than ascii characters and you will see error like ordinal not in range(128). This was the case for me while I was converting list of string in language other than English

I resolved it by using unicode(object)

Drise
  • 4,310
  • 5
  • 41
  • 66
Madhav
  • 721
  • 8
  • 10
14

str(object) will do the trick.

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

Abgan
  • 3,696
  • 22
  • 31
  • 1
    Which method is efficient? `str(any_var)` or `any_var.__str__()` – Kedar.Aitawdekar Sep 15 '16 at 16:49
  • @Kedar.Aitawdekar: Even if there is noticeable difference in execution time (which I doubt, but I encourage you to vefiry it using `timeit` module), you should use `str(any_var)` since it's more readable for human and allows to benefit from cases when `any_var` defines `__repr__()` but doesn't define `__str__()`. – Abgan Oct 11 '16 at 15:22
  • Thanks for your reply. – Kedar.Aitawdekar Oct 13 '16 at 06:38
  • does every class/type in python always allows `str` to be called on it without error? – Charlie Parker Oct 25 '20 at 16:25
  • @CharlieParker : Yes, `str()` can be called freely on any Python object, including classes, modules, function objects etc. It is possible to implement `__str__` on a custom type in a way that would raise an exception, but generally speaking it's possible to make an error in any custom code. ;) – Abgan Aug 26 '21 at 09:21
12

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

miku
  • 181,842
  • 47
  • 306
  • 310
6

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

Philipp
  • 48,066
  • 12
  • 84
  • 109
3

You can use %s like below

>>> "%s" %([])
'[]'
SuperNova
  • 25,512
  • 7
  • 93
  • 64
1

Just use str - for example:

>>> str([])
'[]'
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
1

Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for loop) this might bring up unexpected behaviour:

>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18
PythoNic
  • 303
  • 5
  • 13
0

Use formatting:

"%s" % (x)

Example:

x = time.ctime(); str = "%s" % (x); print str

Output: Thu Jan 11 20:40:05 2018

Apostolos
  • 3,115
  • 25
  • 28