Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to long in python

Tags:

python

Python provides a convenient method long() to convert string to long:

long('234')  

; converts '234' into a long

If user keys in 234.89 then python will raise an error message:

ValueError: invalid literal for long() with base 10: '234.89' 

How should we a python programmer handles scenarios where a string with a decimal value ?

Thank you =)

like image 314
zfranciscus Avatar asked Jan 24 '11 02:01

zfranciscus


People also ask

How will you convert a string to a long in Python?

By converting a string into long we are translating the value of string type to long type. In Python3 int is upgraded to long by default which means that all the integers are long in Python3. So we can use int() to convert a string to long in Python.

Is there long in Python?

In Python 2.7. there are two separate types “int” (which is 32 bit) and “long int” that is same as “int” of Python 3.x, i.e., can store arbitrarily large numbers.

How do you convert a large string to an int in Python?

Strings can be converted to integers by using the int() method. If your string does not have decimal places, you'll most likely want to convert it to an integer by using the int() method.


1 Answers

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

like image 187
Senthil Kumaran Avatar answered Sep 18 '22 21:09

Senthil Kumaran