Python built-in Method - str()
The str()
method is a built-in function in Python that is used to convert an object into a string. The str()
method takes one argument, which is the object that you want to convert into a string. The resulting string will be a human-readable representation of the object.
Here is the syntax for the str()
method:
str(object, encoding='utf-8', errors='strict')Source:www.theitroad.com
The object
parameter is the object that you want to convert into a string. The encoding
parameter is an optional parameter that specifies the character encoding to use for the resulting string. The default encoding is 'utf-8'
. The errors
parameter is an optional parameter that specifies how to handle errors that occur during encoding. The default is 'strict'
, which means that errors will raise an exception.
Here are some examples of using the str()
method:
x = 42 s = str(x) print(s) # output: '42' y = [1, 2, 3] t = str(y) print(t) # output: '[1, 2, 3]'
In the first example, we convert an integer value 42
into a string using the str()
method. In the second example, we convert a list object [1, 2, 3]
into a string.
The str()
method is very useful when you need to convert an object into a string, for example when you want to print or write the object to a file.