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.
str(3.5) # '3.5' str(None) # 'None' str(b"hi", "utf-8") # 'hi'
Try it
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.
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
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()vsrepr().str()targets readers,repr()targets developers and should ideally look like valid code. Containers always userepr()of their items, sostr(["a"])is"['a']".- Defining
__str__. If a class defines only__repr__(),str()falls back to it. Defining only__str__()does not affectrepr(). - Bytes need an encoding.
str(b"abc")without one gives the text"b'abc'"(and, with the-bflag, a warning), not the decoded string. Preferdata.decode("utf-8"). - No implicit conversion.
"a" + 1raisesTypeError; usestr(), an f-string orformat(). - Floats use the shortest representation that round-trips, so
0.1 + 0.2shows0.30000000000000004. - Integers over 4300 digits. Converting a very large
inttostrraisesValueErrorunless the limit is raised withsys.set_int_max_str_digits(). - Subclassing.
stris immutable; subclasses customize via__new__. - Type checks. Use
isinstance(x, str)rather than comparingtype(x).
Related
repr(),format(),int(),bytes(),ascii()- Lessons: Strings, Type conversion, String formatting