ScanSkill

str

This str() function returns a string containing a printable representation of an object.

Syntax

str(object, encoding=encoding, errors=errors)

Here,

  • object: Required. A valid python object.
  • encoding: Optional. Encoding of the object. Default is ‘UTF-8’. (ASCII, utf-8, etc)
  • errors: Optional. Specifies what to do if the decoding fails. (strict, ignore, replace, etc.)

Examples

>>> str(1)
'1'
>>> str([1, 2])
'[1, 2]'
>>> str({'a': 1, 'b': 2})
"{'a': 1, 'b': 2}"
>>> str({1, 2})
'{1, 2}'
>>> str('hello')
'hello'
>>> str("hello")
'hello'
>>> str("""hello""")
'hello'
  • With byte objects
>>> str(b'pyth\\xc3\\xb6n', encoding='utf-8', errors='ignore')
'pythön'
>>>
>>> b_string = bytes('clöudyföx', encoding='utf-8')
b'cl\\xc3\\xb6udyf\\xc3\\xb6x'
>>> str(b_string, encoding='ascii', errors='ignore')
'cludyfx'

Here, errors='ignore' method in str() function ignores the character ö.