DEV Community

Cover image for Type Conversion in Python
Samantha Frangi
Samantha Frangi

Posted on

Type Conversion in Python

Data types are usually one of the first lessons we have when learning a new programming language. Data types in Python would include:

  • String (str)

  • Numeric (int, float)

  • Sequence (list, tuple)

Up until now, I've written in JavaScript and if I wanted to concatenate a string that also included a number it would be very simple.

You can easily write this into a JS file and return a string:

let age = 25;
console.log('im yungbeansprout and im ' + age + ' years old');
Enter fullscreen mode Exit fullscreen mode

Age is a number and this printed in the console as a complete string. This is because of implicit type coercion. JavaScript knows to turn the age into a string type.

If I wanted to do this exact task in Python, I would get a different response. Here's how to write it in Python:

age = 25
print('im yungbeansprout and im ' + age + ' years old')
Enter fullscreen mode Exit fullscreen mode

It would return an error like this:

string-error

This is where type conversion comes in. Type conversion will allow us to turn our current data type (number) into a string so it can join the rest of his friends!

Here is how we would fix this problem:

age = 25
print('im yungbeansprout and im ' + str(age) + ' years old')
Enter fullscreen mode Exit fullscreen mode

Notice how all I did was wrap age in parentheses and write str before it. In Python, this changes our data type.

You can follow this same pattern when converting other data types and now you shouldn't have to worry about your strings returning any errors. Yay!

Top comments (0)