str() Built-in Function
Python str()
Python str() built-in function is used to create a string version of the object that would be passed as argument to it.
In this tutorial, you will learn the syntax of str() function, and then its usage with the help of example programs.
Syntax of str()
The syntax of str() function is
class str(object='')
#or
class str(object=b'', encoding='utf-8', errors='strict')
where
Parameter | Description |
---|---|
object | [Optional] An object. |
encoding | [Optional] The encoding to use to generate the string representation of given object. |
errors | [Optional] Flat that specifies how to handle the encoding errors. |
If no object is provided, str() returns an empty string.
Examples
1. Convert list to string
In this example, we will pass list object as argument to str() function. str() function returns string object.
Python Program
myList = [25, 'hello world', 36.25]
resultString = str(myList)
print(f'Resulting string is - "{resultString}"')
Output
Resulting string is - "[25, 'hello world', 36.25]"
2. str() with no argument
In this example, we will pass no argument to the str() function. str() function should return an empty string.
Python Program
resultString = str()
print(f'Resulting string is - "{resultString}"')
Output
Resulting string is - ""
3. str() with encoding
Let us use the second form of str() function, and pass encoding as well to the str() function.
Python Program
bytes = b'\x65\x66\x67\x68\x69'
resultString = str(bytes, encoding='utf-8')
print(f'Resulting string is - "{resultString}"')
Output
Resulting string is - "efghi"
Summary
In this Python Built-in Functions tutorial, we learned the syntax of str() function, and how to convert any object to its string version using str() function with examples.