我有一些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/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: ")

其他回答

'1.43'.replace('.','',1).isdigit()

只有当存在一个或没有时,它才会返回true。'在数字字符串中。

'1.4.3'.replace('.','',1).isdigit()

将返回false

'1.ww'.replace('.','',1).isdigit()

将返回false

传递dictionary作为参数,它将转换可以转换为float的字符串,并保留其他字符串

def covertDict_float(data):
        for i in data:
            if data[i].split(".")[0].isdigit():
                try:
                    data[i] = float(data[i])
                except:
                    continue
        return data

这是一个简单而有趣的问题。下面给出的解决方案对我来说很好:

import re

val = "25,000.93$"

regex = r"\D"

splitted = re.split(regex, val)
splitted = list(filter(str.isdecimal, splitted))

if splitted:
    if len(splitted) > 1:
        splitted.insert(-1, ".")

    try:
        f = float("".join(splitted))
        print(f, "is float.")
        
    except ValueError:
        print("Not a float.")
        
else:
    print("Not a float.")

重要提示:此解决方案基于分割的最后一个值包含小数位的假设。

你可以使用try-except-else子句,当传递的值不能转换为浮点数时,它将捕获任何转换/值错误


  def try_parse_float(item):
      result = None
      try:
        float(item)
      except:
        pass
      else:
        result = float(item)
      return result

我尝试了上面的一些简单的选项,使用了一个尝试测试转换为浮点数,并发现在大多数回复中有一个问题。

简单测试(按照上面的答案):

entry = ttk.Entry(self, validate='key')
entry['validatecommand'] = (entry.register(_test_num), '%P')

def _test_num(P):
    try: 
        float(P)
        return True
    except ValueError:
        return False

问题出现在:

输入“-”来开始一个负数:

然后尝试float('-'),但失败

你输入一个数字,然后尝试删除所有的数字

然后尝试float("),同样也会失败

我的快速解决方案是:

def _test_num(P):
    if P == '' or P == '-': return True
    try: 
        float(P)
        return True
    except ValueError:
        return False