≡ Menu

HowTo: Python Convert a String Into Integer

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?

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)
Share this tutorial on:
{ 8 comments… add one }
  • Charlie October 20, 2014, 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?

    • Faiza January 25, 2016, 11:06 am

      I DONT REALLY KNOW BUT I CAN FIND OUT FOR YOU AND ANYWAY THTS THE EXACT SAME THING IM STUCK ON

  • Ferran May 7, 2015, 3:11 pm

    Hi, try to write your Decimal like this (decimal):

    x='123.34'
    import decimal
    i=int(decimal(x))
    print(i)
    type(i)
  • Saikiran May 13, 2015, 12:53 pm

    x=’123.34′
    import decimal
    i=int(decimal.Decimal(x))
    print(i)
    type(i)

  • de Bise May 14, 2015, 8:24 am

    Bonjour
    J’ai un problème avec mon programme , puis-je vous le montrer afin que vous m’aidiez ?
    dans mon programme j’aimerai convertir un format str en int afin de faire une série de calcule

  • Lisa Mc Guire November 8, 2015, 11:52 am

    Hi!
    im a python-beginner and dont know much about programming yet..
    so i ve got the “programming in python3” book
    my question:
    page55
    i ve got problems to understand int(s , base)

    it would be nice to get a simple example!
    thnx:)!

  • Anil February 28, 2016, 4:37 pm
    import array
    i=0
    verts = list(xrange(1000))
    f = open("gluon.txt", "r+")
    words = f.read().split()
    for w in words:
        verts[i]=int('w')
        i += 1
    

    Im getting the error:

    Traceback (most recent call last):
      File "C:\Anil\Python\test.py", line 7, in
        verts[i]=int('w')
    ValueError: invalid literal for int() with base 10: 'w'
    

    Please help me

  • tara June 3, 2016, 12:14 pm

    thanks

Leave a Comment


   Tagged with: , , , , , , , ,