Python str()

Python str() builtin function is used to create a string from a Python object, or a Python bytes object with an optionally specified encoding and error handling action.

In this tutorial, we will learn about the syntax of Python str() function, and learn how to use this function with the help of examples.

Syntax

The syntax of str() function with a Python object as parameter is

</>
Copy
str(object='')

where

ParameterRequired/OptionalDescription
objectOptionalA python object. The default value is empty string.

The syntax of str() function with a Python bytes object, encoding and errors as parameters is

</>
Copy
str(object=b'', encoding='utf-8', errors='strict')

where

ParameterRequired/OptionalDescription
objectOptionalA python bytes object.
encodingOptionalEncoding of data in given object.
Possible Values – ascii, big5, utf_8, utf_16, utf_32, or etc.
errorsOptionalThe handling that has to happen when an error occurs while decoding given object using given encoding standard.
Possible Values – strict, ignore, replace, xmlcharrefreplace, backslashreplace, namereplace, or surrogateescape.

Returns

The function returns string object.

Examples

1. str(object)

In this example, we will create a string from list object. Take a list initialized with some elements, and pass this list as argument to str() builtin function.

Python Program

</>
Copy
myList = [2, 4, 6, 8]
myString = str(myList)
print(myString)

Output

[2, 4, 6, 8]

[2, 4, 6, 8] in the output is a string object.

2. str(object, encoding)

In this example, we will create a string from bytes object with specific encoding.

Python Program

</>
Copy
object = b'\x61\x00\x62\x00\x63\x00\x64\x00'
myString = str(object, encoding='utf-16')
print(myString)

Output

abcd

Conclusion

In this Python Tutorial, we have learnt the syntax of Python str() builtin function, and also learned how to use this function, with the help of Python example programs.