The str()
function is used to convert an object into its string representation. It can also be used without any argument to create an empty string.
Syntax:
str() #create an empty string
str(object) #get the string representation of the given object.
When the function is called without an argument, it simply returns an empty string. Example:
str()
//''
When the function is called with an argument, it returns the string representation of the object. Any given object in Python possesses a string representation , rendering all objects as valid arguments to the str()
function. Examples:
str(7)
//'7'
str([1, 2, 3, 5])
//'[1, 2, 3, 5]'
str(('Python', 'Java', 'C++'))
//"('Python', 'Java', 'C++')"
str({1:'one', 2:'two'})
//"{1: 'one', 2: 'two'}"
str(print)
//'<built-in function print>'
str(str)
//"<class 'str'>"
import math
str(math)
//"<module 'math' (built-in)>"
A user defined object can override its default string representation by defining the __str__()
method. For example:
class MyObject():
pass
x =MyObject()
str(x)
//'<MyObject object at 0x000001F129193710>'
class MyObject2():
def __str__(self):
return "A simple object."
y = MyObject2()
str(y)
//'A simple object.'