Skip to content
Tutorials Center
My learning

Topics

Python Reference Β· Built-in Functions

Python str() function

Reference for Python str(): convert any value to a string, decode bytes with an encoding, the difference between str() and repr(), and common pitfalls.

str is both the built-in string type and the function that converts a value to one. str(42) gives "42", str([1, 2]) gives "[1, 2]", and str(obj) calls the object's __str__() method, which is meant to return a readable, user-friendly description.

With bytes and an encoding, str() decodes data into text. Calling str() with no arguments returns the empty string.

Python
str(3.5)        # '3.5'
str(None)       # 'None'
str(b"hi", "utf-8")   # 'hi'

Try it

Python Converting values

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python __str__, __repr__ and decoding errors

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str(object="")
str(object=b"", encoding="utf-8", errors="strict")
Name Description
object The value to convert.
encoding Used when object is bytes, bytearray or a bytes-like object. Defaults to "utf-8".
errors How to handle undecodable bytes: "strict" (raise), "replace", "ignore", ...

Return value: a str.

Raises: UnicodeDecodeError for bytes that do not match the encoding, LookupError for an unknown encoding, and TypeError if encoding or errors is given for a value that is not bytes-like.

Usage notes

  • str() vs repr(). str() targets readers, repr() targets developers and should ideally look like valid code. Containers always use repr() of their items, so str(["a"]) is "['a']".
  • Defining __str__. If a class defines only __repr__(), str() falls back to it. Defining only __str__() does not affect repr().
  • Bytes need an encoding. str(b"abc") without one gives the text "b'abc'" (and, with the -b flag, a warning), not the decoded string. Prefer data.decode("utf-8").
  • No implicit conversion. "a" + 1 raises TypeError; use str(), an f-string or format().
  • Floats use the shortest representation that round-trips, so 0.1 + 0.2 shows 0.30000000000000004.
  • Integers over 4300 digits. Converting a very large int to str raises ValueError unless the limit is raised with sys.set_int_max_str_digits().
  • Subclassing. str is immutable; subclasses customize via __new__.
  • Type checks. Use isinstance(x, str) rather than comparing type(x).