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

PythonServer Side ProgrammingProgramming

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'


raja
Published on 06-Feb-2018 06:57:21
Advertisements