Skip to content
Home » String to Number Type Conversion in Python

String to Number Type Conversion in Python

Spread the love

Today we’ll be talking about numeric data type conversion, and in particular about converting string representations of numbers to numbers.

type conversion

From user input we get strings into the program:

 >>> a = input("What's your name?")
 What's your name? Bill 

But what if you need a number? For example:

 >>> a = input("Enter a number: ")
 Enter a number: 42

 >>> a   # we can print the number
 '42' 

But you can’t use the number in calculations because technically it’s a string, not a number:

 >>> a * 10   # what we get is repetition
 '42424242424242424242' 

If you want the input to be treated as a number you must cast it to an int or float. You can use the int or float function to achieve that:

 >>> x = input("Enter a number: ")
 Enter a number: 5

 >>> int(x) * 10
 50

 >>> float(x) + 3.48
 8.48 

You can cast strings to numbers directly in user’s input:

 >>> x = int(input("Enter x: "))
 Enter x:
 12

 >>> y = int(input("Enter y: "))
 Enter y:
 4

 >>> x * y - x
 36 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Using the eval Function for Type Conversion

We also use the eval function if we need the input to not be treated as a string, but rather as a different data type. For example, we can use it for numbers:

 >>> number = eval(input("What's the number?"))
 What's the number?
 5 

Now the input is no longer treated as a string, but as an integer:

 >>> type(number)
 <class 'int'> 

And it can be used in calculations just like any integer:

 >>> number * 2
 10 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love

Leave a Reply