Python str() – Examples

Python str() Function

Python str() function is used to create a string version of the object that would be passed as argument to it.

In this tutorial, we will learn about str() builtin function in Python, with examples.

Syntax – str()

The syntax of str() function is

class str(object='')
#or
class str(object=b'', encoding='utf-8', errors='strict')

str() function takes a Python object as an argument and returns its string value. If no object is provided, str() returns an empty string.

str() with List object as Argument

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}"')
Run

Output

Resulting string is - "[25, 'hello world', 36.25]"

str() with No Object as 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}"')
Run

Output

Resulting string is - ""

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}"')
Run

Output

Resulting string is - "efghi"

Summary

In this tutorial of Python Examples, we learned the syntax of str() function, and how to convert any object to its string version using str() function with examples.