Python,判断字符串应该转换为整型还是浮点型
我想把一个字符串转换成最合适的数据类型:整数(int)或者浮点数(float)。
我有两个字符串:
value1="0.80" #this needs to be a float
value2="1.00" #this needs to be an integer.
我该怎么判断 value1 应该是浮点数,而 value2 应该是整数呢?
10 个回答
7
我需要处理一个情况,就是在比较两个XML文档时,要确保'1.0'能被转换成'1'。所以我写了这个函数来帮我解决这个问题。我还觉得其他一些解决方案在处理字符串'True'或'False'时可能会出错。无论如何,这个函数对我来说效果很好。希望它也能对你有帮助。
from ast import literal_eval
def convertString(s):
'''
This function will try to convert a string literal to a number or a bool
such that '1.0' and '1' will both return 1.
The point of this is to ensure that '1.0' and '1' return as int(1) and that
'False' and 'True' are returned as bools not numbers.
This is useful for generating text that may contain numbers for diff
purposes. For example you may want to dump two XML documents to text files
then do a diff. In this case you would want <blah value='1.0'/> to match
<blah value='1'/>.
The solution for me is to convert the 1.0 to 1 so that diff doesn't see a
difference.
If s doesn't evaluate to a literal then s will simply be returned UNLESS the
literal is a float with no fractional part. (i.e. 1.0 will become 1)
If s evaluates to float or a float literal (i.e. '1.1') then a float will be
returned if and only if the float has no fractional part.
if s evaluates as a valid literal then the literal will be returned. (e.g.
'1' will become 1 and 'False' will become False)
'''
if isinstance(s, str):
# It's a string. Does it represnt a literal?
#
try:
val = literal_eval(s)
except:
# s doesn't represnt any sort of literal so no conversion will be
# done.
#
val = s
else:
# It's already something other than a string
#
val = s
##
# Is the float actually an int? (i.e. is the float 1.0 ?)
#
if isinstance(val, float):
if val.is_integer():
return int(val)
# It really is a float
return val
return val
这个函数的单元测试输出结果是:
convertString("1")=1; we expect 1
convertString("1.0")=1; we expect 1
convertString("1.1")=1.1; we expect 1.1
convertString("010")=8; we expect 8
convertString("0xDEADBEEF")=3735928559; we expect 3735928559
convertString("hello")="hello"; we expect "hello"
convertString("false")="false"; we expect "false"
convertString("true")="true"; we expect "true"
convertString("False")=False; we expect False
convertString("True")=True; we expect True
convertString(sri.gui3.xmlSamples.test_convertString.A)=sri.gui3.xmlSamples.test_convertString.A; we expect sri.gui3.xmlSamples.test_convertString.A
convertString(<function B at 0x7fd9e2f27ed8>)=<function B at 0x7fd9e2f27ed8>; we expect <function B at 0x7fd9e2f27ed8>
convertString(1)=1; we expect 1
convertString(1.0)=1; we expect 1
convertString(1.1)=1.1; we expect 1.1
convertString(3735928559)=3735928559; we expect 3735928559
convertString(False)=False; we expect False
convertString(True)=True; we expect True
下面是单元测试的代码:
import unittest
# just class for testing that the class gets returned unmolested.
#
class A: pass
# Just a function
#
def B(): pass
class Test(unittest.TestCase):
def setUp(self):
self.conversions = [
# input | expected
('1' ,1 ),
('1.0' ,1 ), # float with no fractional part
('1.1' ,1.1 ),
('010' ,8 ), # octal
('0xDEADBEEF',0xDEADBEEF), # hex
('hello' ,'hello' ),
('false' ,'false' ),
('true' ,'true' ),
('False' ,False ), # bool
('True' ,True ), # bool
(A ,A ), # class
(B ,B ), # function
(1 ,1 ),
(1.0 ,1 ), # float with no fractional part
(1.1 ,1.1 ),
(0xDEADBEEF ,0xDEADBEEF),
(False ,False ),
(True ,True ),
]
def testName(self):
for s,expected in self.conversions:
rval = convertString(s)
print 'convertString({s})={rval}; we expect {expected}'.format(**locals())
self.assertEqual(rval, expected)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
26
Python中的float
对象有一个叫做is_integer
的方法:
from ast import literal_eval
def parses_to_integer(s):
val = literal_eval(s)
return isinstance(val, int) or (isinstance(val, float) and val.is_integer())
33
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够正确地理解和使用这些数据,我们通常需要对它们进行“清洗”或者“格式化”。
数据清洗就是把那些不符合要求的数据去掉,或者把它们转换成我们需要的格式。比如说,如果用户输入了一个电话号码,但格式不对,我们就需要把它调整成标准格式,这样程序才能正确处理。
格式化则是把数据按照一定的规则进行整理,比如把日期从“年-月-日”的格式转换成“日/月/年”的格式。这样做的目的是为了让数据更容易阅读和理解。
总之,处理数据的过程就是确保我们得到的数据是干净的、整齐的,这样才能让程序顺利运行,不会因为数据的问题而出错。
def isfloat(x):
try:
a = float(x)
except (TypeError, ValueError):
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except (TypeError, ValueError):
return False
else:
return a == b