我有一些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块中,看看它是否成功,如这个问题所述。

有人有其他想法吗?对分区和尝试/捕获方法的相对优点有什么看法?


当前回答

您可以创建一个函数isfloat(),并在整数和浮点数中使用isdigit(),但不能使用您期望的字符串。

a = raw_input('How much is 1 share in that company? \n')

def isfloat(num):
    try:
        float(num)
        return True
    except:
        return False
       
while not isfloat(a):
    print("You need to write a number!\n")
    a = raw_input('How much is 1 share in that company? \n')

其他回答

似乎很多正则表达式都错过了这样或那样的事情。到目前为止,这对我来说是有效的:

(?i)^\s*[+-]?(?:inf(inity)?|nan|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*$

它允许无穷大(或无穷大)与符号,nan,没有数字之前 十进制,以及前导/尾随空格(如果需要)。^和$是 需要避免将1.2f-2部分匹配为1.2。

如果需要解析某些文件,可以使用[ed]而不是e 其中D用于双精度科学计数法。你会 想要更换它之后或只是更换他们之前检查,因为 float()函数不允许这样做。

一个简单的函数,不需要try和except操作就可以得到数字的类型

def number_type(number):
    if number.isdigit():
        return int(number)
    elif number.replace(".","").isdigit():
        return float(number)
    else:
        return(type(number))

函数is_digit(str)的简化版本,它在大多数情况下都足够了(不考虑指数符号和“NaN”值):

def is_digit(str):
    return str.lstrip('-').replace('.', '').isdigit()

我会用。

try:
    float(element)
except ValueError:
    print "Not a float"

..这很简单,也很有效。注意,如果元素是例如1<<1024,它仍然会抛出OverflowError。

另一种选择是正则表达式:

import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
    print "Not float"

我正在寻找一些类似的代码,但看起来使用try/excepts是最好的方法。 这是我正在使用的代码。它包括一个在输入无效时的重试函数。我需要检查输入是否大于0,如果是,则将其转换为浮点数。

def cleanInput(question,retry=False): 
    inputValue = input("\n\nOnly positive numbers can be entered, please re-enter the value.\n\n{}".format(question)) if retry else input(question)
    try:
        if float(inputValue) <= 0 : raise ValueError()
        else : return(float(inputValue))
    except ValueError : return(cleanInput(question,retry=True))


willbefloat = cleanInput("Give me the number: ")