Python str() function
Python str() function 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
Python str() function example
Example 1: Demonstration of str() function
Python3
# Python program to demonstrate# strings# Empty strings = str()print(s)# String with valuess = str("GFG")print(s) |
Output:
GFG
Example 2: Converting to string
Python3
# Python program to demonstrate# stringsnum = 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 Unicode
- replace: It replaces the unencodable Unicode with 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 an 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.






Please Login to comment...