Skip to content

Python str() function

  • by

Python str() function is used to convert the specified value into a string. This method returns the string representation of a given object.

str(object, encoding=encoding, errors=errors) 
  • 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)

Python str() function

Simple example code.

# string
name = str('John')
print(type(name), name)

# integer
age = str(100)
print(type(age), age)

# numeric string
height = str('100ft')
print(type(height), height)

Output:

Python str() function

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

Comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading