HowTo: Python Convert a String Into Integer

by on November 9, 2011 · 1 comment· LAST UPDATED August 9, 2013

in , ,

How do I convert a string such as x='12345' to an integer (int) under Python programming language? How can I parse python string to integer?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPython
Estimated completion time1m
You need to use int(s) to convert a string or number to an integer. For testing purpose, defined a string called x='123456', run:

You may also need to use float(s) to convert a string or number to a floating point number or combination of both as follows:


int(s)
float(s)
int(float(s))

Examples

 
x = '123456'
 

Confirm the object type:

 
type(x)
 

Sample outputs:

<type 'str'>

Convert a string to an int and store it to i, run:

 
i = int(x)
type(i)
 

Sample outputs:

<type 'int'>

However, the following string to int will fail:

 
x='123456.334'
y=int(x)
 

Sample outputs:

ValueError                                Traceback (most recent call last)
/home/vivek/ in ()
ValueError: invalid literal for int() with base 10: '123456.334'

Try the following solution:

 
x='123456.334'
y=int(float(x))
type(x)
type(y)
print y
a='12.5'
b='13.5'
print( int(float(a))+ int(float(b)) )
 

Finally, you can also use floating point class for decimal arithmetic:

 
x='123.34'
import decimal
i=int(Decimal(x))
print(i)
type(i)
 
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 1 comment… read it below or add one }

1 Charlie October 20, 2014 at 8:42 pm

Hey, I get an error output when I input i=int(Decimal(x)), NameError: name ‘Decimal’ is not defined. Forgive me, I’m new to Python. Can you explain this?

Reply

Leave a Comment

Tagged as: , , , , , , , ,

Previous Faq:

Next Faq: