Skip to main content

Type Conversion

Type conversion is a common requirement in programming, and both Python and JavaScript provide methods specifically for type conversion.


Assuming there is a hard disk with a capacity of 8192MB (as a string), please convert the capacity of this hard disk to the TB unit and save the conversion result in an integer variable.

JavaScript implementation

let gb = '8192MB';
let tb = parseInt(gb) / 1024
let intTb = parseInt(tb)
console.log(`The capacity of this hard disk is: ${intTb}TB`)

Python implementation

gb = '8192MB'
int_tb = int(gb[:-2]) // 1024
print(f"The capacity of this hard disk is: {int_tb}TB")

Code Highlight

  • Python uses built-in functions with the same name as the type (e.g., str(some_value), bool(some_value), etc.) for data conversion, while JavaScript uses built-in functions with the parse prefix.
  • In Python, a string like '8192MB' cannot be directly converted to an integer or float because it is incompatible with these two types, while JavaScript can convert it to an integer using parseInt.
  • Python can use string slicing syntax ([start:end]) to get a substring of a string.

Difference Quick View

Convert to integerparseInt(myVal) or Number(myVal)int(my_val)
Convert to floatparseFloat(myVal) or Number(myVal)float(my_val)
Convert to stringmyVal.toString() or String(myVal)str(my_val)
Convert to booleanBoolean(myVal)bool(val)
Convert to array-list(my_val)
Convert to object-dict(my_val)