Home » Learn Python » Getting Started » Casting and Conversion

Casting and Conversion

In Python, and in most programming languages, the value 123 is a very different thing to the string “123”

The first is a number that you can use in calculations. The second is some text: you can’t use it in calculations.

A common thing to do is convert text representing a number to an actual number, or the opposite: we might want to convert a number to text so we can use string methods on it.

We can also convert one kind of number to another; for example, we can convert an integer to a floating point number.

Simple conversions like these are often called casts. The conversion is known as casting.

We can perform a cast using one of several built-in Python functions. The most important functions used in this way are:

  • int() — convert to an integer
  • float() – convert to a floating-point number
  • str() — convert to a string

Casting: Some Examples

value = "123"
print(type(value))

# Convert the string to an integer
# using the int() builtin function.
# Then assign the result back to 
# the original variable.

value = int(value)
print(type(value))

# Now convert to a float instead.
value = float(value)
print(type(value))

# And back to a string.
value = str(value)
print(type(value))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'str'>

In the next article we’ll use casting to help implement a program that converts a temperature in Fahrenheit to a temperature in Celsius.

Leave a Reply

Blog at WordPress.com.

%d