How to use the str() function in Python
Overview
str() is a Python function that converts a given value into a string.
Syntax
str(object, encoding=encoding, errors=errors)
Parameters
-
object: This is the object whose string representation will be returned. -
encoding: It represents the encoding of the object. The default value UTF-8 is used if it is not specified. -
errors: This results from a failed decoding attempt.
Return value
The str() function returns the string representation of the given object.
Code example
The following code shows how to use the str() function in Python:
# create a variablenum = 50# store the valueresult = str(num)print(result, type(result))
Code explanation
- Line 2: We create a variable named
num. - Line 4: We use the
str()to convert the value to a string and then assign the result to a new variable namedresult. - Line 6: The result with its type is displayed.