How to convert an object x to a string representation in Python?


Most commonly used str() function from Python library returns a string representation of object.

>>> no=100
>>> str(no)
'100'
>>> L1=[1,2,3,4]
>>> str(L1)
'[1, 2, 3, 4]'
>>> d={'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"

However, repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous.

>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(L1)
'[1, 2, 3, 4]'
>>> repr(no)
'100'


Updated on: 24-Feb-2020

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements