The str()
method returns the string representation of a given object.
Example
# string representation of Adam
print(str('Adam'))
# Output: Adam
str() Syntax
The syntax of str()
is:
str(object, encoding='utf-8', errors='strict')
Here, encoding and errors parameters are only meant to be used when the object type is bytes or bytearray.
str() Parameters
The str()
method takes three parameters:
- object - whose string representation is to be returned
- encoding - that the given byte object needs to be decoded to (can be UTF-8, ASCII, etc)
- errors - a response when decoding fails (can be strict, ignore, replace, etc)
Note: There are six types of errors: strict, ignore, replace, xmlcharrefreplace, namereplace, backslashreplace. The default error is strict.
str() Return Value
The str()
method returns:
- a printable string representation of a given object
- string representation of a given byte object in the provided encoding
Example 1: Python() String
# string representation of Luke
name = str('Luke')
print(name)
# string representation of an integer 40
age = str(40)
print(age)
# string representation of a numeric string 7ft
height = str('7ft')
print(height)
Output
Luke 40 7ft
In the above example, we have used the str()
method with different types of arguments like string, integer, and numeric string.
Example 2: str() with Byte Objects
We can use the str()
method with byte objects which are defined by the bytes() method.
In this case, we need to specify the encoding that we want to convert the byte objects to and the type of error checking that the str()
method can perform.
# declare a byte object
b = bytes('pythön', encoding='utf-8')
# convert a utf-8 byte object to ascii with errors ignored
print(str(b, encoding='ascii', errors='ignore'))
# convert a utf-8 byte object to ascii with strict error
print(str(b, encoding='ascii', errors='strict'))
Output
pythn UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
In the first example, we have created a byte object b with the string 'pythön'
and the encoding utf-8
.
We have passed the b object to the str()
method and specified the encoding to ascii
.
Here, we have set the errors
parameter to ignore
so, the str()
method ignores the character 'ö'
. Since the method can't decode this character to ascii
, we get the output pythn.
Similarly, in the second example, we've set the error to strict
. In this case, the str()
method will take the character 'ö'
into account and produce UnicodeDecodeError as the output.
Also Read: