Programming Search⌘K

Featureintro

Type conversions

Also called Python type casting, int() float() str() bool(), convert string to number in Python, __index__, implicit conversion in Python.

Python converts a value by calling the target type, such as int(x), float(x) or str(x). Only numbers convert implicitly, and "1" + 1 is a TypeError. Classes can define __int__, __index__ and __str__.

Language
Python

Synopsis

print(int("42"), float("4.2"), str(42), complex("1+2j"), bool("x"))
print(list("abc"), tuple([1, 2]), int(4.9), float(3), str([1, "a"]))
print("1" + str(1), int("1") + 1)
Output
42 4.2 42 (1+2j) True
['a', 'b', 'c'] (1, 2) 4 3.0 [1, 'a']
11 2

Each conversion calls a type. "1" + str(1) joins strings, and int("1") + 1 adds numbers.

Semantics

r1. The constructors int(), float() and complex() "can be used to produce numbers of a specific type".3 list and tuple are not functions but sequence types, and calling them with an iterable gives a list or a tuple.1 Example: convert.

r2. int() with a string reads an integer in a base, and float() reads a decimal number or a NaN or infinity. A string in the wrong form raises ValueError.1 Conversion from a float to an int "truncates, discarding the fractional part".3 Example: bad-string.

r3. str(object) returns type(object).__str__(object), the informal, nicely printable string representation. If the object has no __str__() method, str() returns repr(object).2 __str__() "must be a str object".4 Example: convert.

r4. bool(x) converts with "the standard truth testing procedure", so it returns False for a false or omitted argument and True otherwise.1 Example: convert.

r5. A class takes part in the numeric conversions with special methods. int(x) returns x.__int__() if it is defined, or else x.__index__().1 __index__() is called "whenever Python needs to losslessly convert the numeric object to an integer object", for example in slicing and in bin(), hex() and oct(). If __int__(), __float__() and __complex__() are not defined, int(), float() and complex() fall back to __index__().4 Example: index-method.

r6. For +, the arguments "must either both be numbers or both be sequences of the same type". Numbers are converted to a common real type, and sequences are concatenated.5 So the only implicit conversions of + are between numbers. Example: no-implicit-str.

Examples

__index__() makes an object usable as an integer in int(), float(), bin() and indexing (rule r5).

class Seven:
    def __index__(self):
        return 7

s = Seven()
print(int(s), float(s), bin(s), "abcdefgh"[s])
Output
7 7.0 0b111 h

Pitfalls

"1" + 1

A string and a number do not mix with + (rule r6). Convert one side explicitly, to str to join text or to int to add.

This code raises TypeError, on purpose.

count = 1
print("count: " + count)

int("4.2") and int("")

int() does not read a decimal point or an empty string (rule r2). Read the text with float() first, or check the input.

This code runs but gives a wrong answer on purpose.

for text in ["42", "4.2", ""]:
    try:
        print(int(text))
    except ValueError:
        print("ValueError for", repr(text))
Output
42
ValueError for '4.2'
ValueError for ''

"3" == 3 is false

== does not convert a string to a number, so text read from input never equals a number. Convert the text first.

This code runs but gives a wrong answer on purpose.

print("3" == 3, int("3") == 3, 3 == 3.0)
Output
False True True

Comparison

In Go, "A conversion changes the type of an expression to the type specified by the conversion", and an explicit conversion has the form T(x).6 Python uses the same form, a call of the type, such as int(x) or str(x). In Python the call is an ordinary function call of a class, so a class can control it with special methods (rule r5).

References

  1. Built-in Functions, Python 3.15 documentation, int(), float(), complex(), bool(), list(), tuple()
  2. Built-in Types, Python 3.15 documentation, str()
  3. Built-in Types, Python 3.15 documentation, Numeric Types - int, float, complex
  4. The Python Language Reference, Python 3.15, 3.3.1 object.__str__(); 3.3.8 object.__index__()
  5. The Python Language Reference, Python 3.15, 6.7. Binary arithmetic operations
  6. The Go Programming Language Specification, Conversions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source