我有一些Python代码,它会遍历一个字符串列表并将它们转换为整数或浮点数(如果可能的话)。对于整数,这很容易实现。
if element.isdigit():
newelement = int(element)
浮点数更难处理。目前我正在使用 partition('.')
来分割字符串,并检查一侧或两侧是否为数字。
partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
newelement = float(element)
这个方法可行,但是显然if语句有点复杂。我考虑的另一个解决方案是用try/catch代码块来尝试转换并查看是否成功,就像这个问题中描述的那样。
大家有其他的想法吗?对分隔符和try/catch方法的优劣有什么看法?
print(type("1"));print(type(int("1")))
,输出:<class 'str'>
<class 'int'>
?这不是从str
到int
的类型转换吗? - ggorlen.isdigit()
而不是.isnumeric()
来判断正整数? - Charlie Parker