在python中将字符串转换为long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4777972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting string to long in python
提问by zfranciscus
Python provides a convenient method long() to convert string to long:
Python 提供了一个方便的方法 long() 将字符串转换为 long:
long('234')
; converts '234' into a long
; 将 '234' 转换为 long
If user keys in 234.89 then python will raise an error message:
如果用户键入 234.89,那么 python 将引发错误消息:
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 ?
我们 Python 程序员应该如何处理带有十进制值的字符串的场景?
Thank you =)
谢谢你=)
采纳答案by Senthil Kumaran
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, floatthe 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 intto provide the key as well.
long只能接受可以以 10 为基数结尾的字符串转换。所以,小数造成了伤害。您可以做的是,float调用long. 如果您的程序在 Python 2.x 上运行,其中 int 和 long 差异很重要,并且您确定您没有使用大整数,那么您也可以使用 usingint提供密钥。
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
所以,答案是long(float('234.89'))或者它可能只是int(float('234.89'))如果你不使用大整数。另请注意,这种差异在 Python 3 中不会出现,因为 int 默认升级为 long。python3中的所有整数都很长,调用covert只是int
回答by payne
Well, longs can't hold anything but integers.
好吧,longs 只能容纳整数。
One option is to use a float: float('234.89')
一种选择是使用浮点数: 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'))
另一种选择是截断或舍入。从 float 转换为 long 将为您截断: 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

