by : D.BHUVANESHWARI
str() vs repr() function in python
str() :
This function is used to represent the string. Python programming language is used to convert the specified value into a string datatype.
str() function Syntax:
str(object, encoding=’utf-8?, errors=’strict’)
object: The object whose string representation is to be returned.
encoding : Encoding of the given object.
error : response when decoding fails.
Example: In the given example, we assign an integer value to a variable and convert that integer variable to the string variable.
a=15 b=str(a) print(b)
Output
: 15
a=50 s=str(a) print(s, type(s)) a=50.4 s=str(a) print(s, type(s))
Output:
50 <calss 'str'> 50.4 <class 'str'>
repr() :
repr() function is used to get the complete information of an object. It returns the string representation passed implicitly to the eval() function.
Syntax of repr() function:
repr(object)
object: The object whose printable representation is to be returned.
Here we assign an integer value of 100 to a variable x and the repr() of x is returning the value 100 as a string class.
x=100 print(type(repr(x))) print(repr(['a', 'b', 'c'])) print(repr(5.0/323.5))
Output:
<class 'str'> ['a', 'b', 'c'] 0.015455950540958269
class Preson: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person(name='{self.name}', age={self.age})" person = Person("John", 25) print(repr(person))
Output:
Person(name='John', age=25)
str() vs repr():
In Python, the str() and repr() functions are used to obtain string representations of objects. Both of the functions can be helpful in debugging or printing useful information about the object.
class Complex: def __init__(self, real, imag): self.real = real self.imag = imag def __repr__(self): return 'Rational(%s, %s)' % (self.real, self.imag) def __str__(self): return '%s + i%s' % (self.real, self.imag) a=Complex(50,100) print(str(a)) print(repr(a))
Output:
50 + i100 Rational(50, 100)