The built-in function str() is used to convert the given object into the string format. The behavior of the output string depends on the arguments encoding and errors.
str(object, encoding='utf-8', errors='strict') #where object is whoes string representation needed
Takes three parameters. The argument errors are of six types as below
strict - which raises a UnicodeDecodeError exception on failure.
ignore - ignores the unencodable Unicode from the result
replace - replaces the unencodable Unicode to a question mark
xmlcharrefreplace - instead of unencodable Unicode inserts XML character reference
backslashreplace - instead of unencodable Unicode it inserts a \uNNNN espace sequence
namereplace - instead of unencodable Unicode it inserts a \N{...} escape sequence
Parameter | Description | Required / Optional |
---|---|---|
object | The object whose string representation is to be returned. If not provided, returns the empty string | Required |
encoding | Encoding of the given object. Defaults of UTF-8 when not provided | Optional |
errors | Response when decoding fails. Defaults to 'strict' | Optional |
This returns a string object which is in a printable format. If parameter encoding and errors are missing, the str() function internally calls the __str__() method of an object.
Input | Return Value |
---|---|
If object | string |
output = str(25)
print(output)
Output:
25
# bytes
byt = bytes('pythön', encoding='utf-8')
print(str(byt, encoding='ascii', errors='ignore'))
Output:
pythn
If the object is bytes or bytearray, str() internally calls bytes.decode(encoding, errors).