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 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 = 100 s = str (num) print (s, type (s)) num = 100.1 s = 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...