converting string to long in 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 ?
Than开发者_如何学编程k you =)
long
can 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
Well, longs can't hold anything but integers.
One option is to use a float: float('234.89')
The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))
>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L
精彩评论