The str () function in Python

The str () function in Python takes an object as a string.

In Python, the str () function returns the selected object as a string.

The syntax of the str () function in Python

The str () function in Python has the syntax:

str(object, encoding='utf-8', errors='strict')

Parameters of the str () function

The str () function has 3 parameters:

  1. Object : An object that can be displayed as a string. If not supplied, the result is an empty string.
  2. encoding : Encoding of an object. If not provided, the default encoding is UTF-8.
  3. errors : Respond when encoding fails. The default value is 'strict'.

There are 6 types of errors:

  1. strict : The default response raises the UnicodeDecodeError exception when an error occurs
  2. ignore : Removes Unicode which cannot be encoded in the result
  3. replace : Replace non-Unicode encoding with a question mark
  4. xmlcharrefreplace : Insert an XML character reference instead of Unicode that cannot be encoded
  5. blackslashreplace : Insert a string uNNNN instead of Unicode which cannot be encoded
  6. nameraplace : Insert a string N {.} instead of Unicode which cannot be encoded
The str () function in Python Picture 1The str () function in Python Picture 1 The str () function in Python returns the string form of an object

The return value of the str () function

The str () function returns a string that is considered to be an unofficial or printable representation of an object.

Example 1: Converting an object to a string using str ()

If two encoding and errors parameters are not provided, the str () function calls the internal __str __ () method of an object.

If the __str __ () method cannot be found , it will call the repr (obj) function instead.

For example:

NamePage = str('TipsMake.com') print(NamePage)

When running the program, the result we get is:

TipsMake.com

Note: The resulting variable will contain a string.

Example 2: How does str () function with bytes?

If the encoding and errors parameters are provided, the first parameter - the object - will have to be a byte object (bytes or bytearray).

If the object is in the form of bytes or bytearray , the str () function will call the bytes.decode (ecoding, errors) method .

Besides, it will get the byte object in the buffer before calling the decode () method .

For example

# str() handling objects in the form of bytes b = bytes('TipsMake', encoding='utf-8') print(str(b, encoding='ascii', errors='ignore'))

The result is:

TipsMake

Here, the character ö cannot decode in ASCII. Therefore, it will cause an error. However, we have set the errors = 'ignore' parameter so Python will ignore the non-decode characters with the str () function .

  1. Python functions built in
  2. What is Python? Why choose Python?
  3. The for loop in Python
4 ★ | 1 Vote