The str() function of Python returns the string version of the object.
Syntax: str(object, encoding=’utf-8?, errors=’strict’)
Parameters:
- object: The object whose string representation is to be returned.
- encoding: Encoding of the given object.
- errors: Response when decoding fails.
Returns: String version of the given object
Example 1:
Python3
# Python program to demonstrate # strings # Empty string s = str() print(s) # String with values s = str("GFG") print(s) |
Output:
GFG
Example 2: Converting to string
Python3
# Python program to demonstrate # strings num = 100s = str(num) print(s, type(s)) num = 100.1s = str(num) print(s, type(s)) |
Output:
100 <class 'str'> 100.1 <class 'str'>
Errors in String
There are six types of error taken by this function.
- strict (default): it raises a UnicodeDecodeError.
- ignore: It ignores the unencodable Unicodet
- replace: It replaces the unencodable Unicode to a question mark
- xmlcharrefreplace: It inserts XML character reference instead of the unencodable Unicode
- backslashreplace: inserts a \uNNNN espace sequence instead of unencodable Unicode
- namereplace: inserts a \N{…} escape sequence instead of unencodable Unicode
Example:
Python3
# Python program to demonstrate # str() a = bytes("ŽString", encoding = 'utf-8') s = str(a, encoding = "ascii", errors ="ignore") print(s) |
Output:
String
In the above example, the character Ž should raise an error as it cannot be decoded by ASCII. But it is ignored because the errors is set as ignore.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

