Type Conversion

Converting to Integer

  1. # string to int
  2. int("42")
  3. #ans: 42
  4. int("100")
  5. #ans: 100
  6. #ans: float to int (truncates)
  7. int(3.14)
  8. #ans: 3
  9. int(9.99)
  10. #ans: 9

Converting to Float

  1. # string to float
  2. float("3.14")
  3. #ans: 3.14
  4. #ans: int to float
  5. float(42)
  6. #ans: 42.0
  7. float(0)
  8. #ans: 0.0

Converting to String

  1. # int to string
  2. str(42)
  3. #ans: "42"
  4. #ans: float to string
  5. str(3.14)
  6. #ans: "3.14"
  7. #ans: bool to string
  8. str(True)
  9. #ans: "True"

Converting to Boolean

  1. # number to bool
  2. bool(1)
  3. #ans: True
  4. bool(0)
  5. #ans: False
  6. bool(-5)
  7. #ans: True
  8. #ans: string to bool
  9. bool("")
  10. #ans: False
  11. bool("text")
  12. #ans: True

Boolean from Other Types

  1. # list to bool
  2. bool([])
  3. #ans: False
  4. bool([1, 2])
  5. #ans: True
  6. #ans: None to bool
  7. bool(None)
  8. #ans: False

Exercises - Part 1

  1. # what is the result?
  2. int("100")
  3. #ans: 100
  4. # what happens?
  5. int("3.14")
  6. #ans: ValueError

Exercises - Part 2

  1. # float from string?
  2. float("3.14")
  3. #ans: 3.14
  4. # bool from number?
  5. bool(0)
  6. #ans: False
  7. bool(1)
  8. #ans: True
  9. bool(-1)
  10. #ans: True

Exercises - Part 3

  1. # bool from string?
  2. bool("")
  3. #ans: False
  4. bool("False")
  5. #ans: True (any non-empty string is True)

Exercises - Part 4

  1. # string from bool?
  2. str(True)
  3. #ans: "True"
  4. # int from bool?
  5. int(False)
  6. #ans: 0
  7. int(True)
  8. #ans: 1

Exercises - Part 5

  1. # what about this?
  2. int(" 42 ")
  3. #ans: 42 (whitespace is stripped)
  4. # edge case?
  5. int("0b101", 2)
  6. #ans: 5 (binary to int)

Exercises - Part 6

  1. # what happens?
  2. float("inf")
  3. #ans: inf (infinity)
  4. # string to int base?
  5. int("FF", 16)
  6. #ans: 255 (hex to int)

Exercises - Part 7

  1. # float to int?
  2. int(3.9)
  3. #ans: 3 (truncates, doesn't round)
  4. # bool from empty?
  5. bool({})
  6. #ans: False

Google tag (gtag.js)