Python Casting

Specify Variable Type

Sometimes you may need to specify the type of a variable. This can be done through casting. Python is an object-oriented language, so it uses classes to define data types, including their primitive types.

Therefore, use constructor functions to complete conversions in Python:

  • int() - Construct integers (by truncating the logarithm) using integer literals, floating-point literals, or string literals representing whole numbers
  • float() - Construct floating-point numbers (providing a string representation of a floating-point number or integer) using integer literals, floating-point literals, or string literals
  • str() - Construct strings using various data types, including strings, integer literals, and floating-point literals

Example

Integers:

x = int(1)   # x will be 1
y = int(2.5) # y will be 2
z = int("3") # z will be 3

Run Example

Example

Floating Point Numbers:

x = float(1)     # x will be 1.0
y = float(2.5)   # y will be 2.5
z = float("3")   # z will be 3.0
w = float("4.6")# w will be 4.6

Run Example

Example

String:

x = str("S2") # x will be 'S2'
y = str(3)    # y will be '3'
z = str(4.0)  # z will be '4.0'

Run Example