Type Coercion with StringsΒΆ
We will now explore under what situations we are able to convert between str
objects and int
or float
objects.
We can convert a str
object to an int
or a float
if the value contained within the string makes sense as the new data type.
a_str = '61'
a_int = int(a_str)
a_float = float(a_str)
print(a_int)
print(a_float)
61
61.0
b_str = '7.93'
b_float = float(b_str)
print(b_float)
7.93
Since the value of b_str
is not interpretable as an integer, we will get an error if we attempt to coerce it to an integer.
b_int = int(b_str)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-c64df22698bc> in <module>
----> 1 b_int = int(b_str)
ValueError: invalid literal for int() with base 10: '7.93'
If we are very insistent about coercing b_int
to an integer, we can first coerce it into a float, and then an integer.
b_int = int(float(b_str))
print(b_int)
We can always convert an int
or a float
object to a str
using the str()
function.
x_float = 4.5
x_str = str(x_float)
print(x_str)
y_int = 8675409
y_str = str(y_int)
print(y_str)
Converting numerical values to strings can be very useful if we want to output a message that contains a mixture of predetermined text, as well as numeric values that are stored in variables. Converting the numeric portions of the message to strings allowed them to be concatenated with the rest of the text.
Consider the following example.
z = 3.56
z2 = z**2
print('The square of ' + str(z) + ' is ' + str(z2) + '.')
We could have obtained the same result as above without using coercion by passing multiple arguments to the print()
function and setting the sep
parameter equal to the empty string, as shown below.
print('The square of ', z, ' is ', z2, '.', sep='')