Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种更像python的方法来测试一个对象是数字还是返回它的值?_Python_Python 2.7 - Fatal编程技术网

有没有一种更像python的方法来测试一个对象是数字还是返回它的值?

有没有一种更像python的方法来测试一个对象是数字还是返回它的值?,python,python-2.7,Python,Python 2.7,我还没有尝试过decorator或函数中的函数,但目前这种非pythonic方法似乎有点复杂。我不喜欢当我检查返回类型3次时,我需要重复我自己的方式 欢迎提出任何建议,特别是如果可以优雅地处理重复。请注意,我对测试对象是否为数字的大量参考并不感兴趣,因为我相信这一部分包含在我的解决方案中。我对处理退货类型的3倍重复感兴趣。此外,虽然我欣赏locale方法是处理国际化的更严格的方法,但我更喜欢让调用者在选择字符时更灵活的简单性 谢谢 def is_number(obj, thousand_sep=

我还没有尝试过decorator或函数中的函数,但目前这种非pythonic方法似乎有点复杂。我不喜欢当我检查返回类型3次时,我需要重复我自己的方式

欢迎提出任何建议,特别是如果可以优雅地处理重复。请注意,我对测试对象是否为数字的大量参考并不感兴趣,因为我相信这一部分包含在我的解决方案中。我对处理退货类型的3倍重复感兴趣。此外,虽然我欣赏locale方法是处理国际化的更严格的方法,但我更喜欢让调用者在选择字符时更灵活的简单性

谢谢

def is_number(obj, thousand_sep=',', decimal_sep=None, return_type='b'):
    """ determines if obj is numeric.

    if return_type = b, returns a boolean True/False
    otherwise, it returns the numeric value

    Examples
    --------
    >>> is_number(3)
    True
    >>> is_number('-4.1728')
    True
    >>> is_number('-4.1728', return_type='n')
    -4.1728
    >>> is_number(-5.43)
    True
    >>> is_number("20,000.43")
    True
    >>> is_number("20.000,43", decimal_sep=",", thousand_sep=",")
    True
    >>> is_number("20.000,43", decimal_sep=",", thousand_sep=".", return_type="n")
    20000.43
    >>> is_number('Four')
    False
    # I am a few light years away from working that one out!!!
    """
    try:
        if is_string(obj):
            if decimal_sep is None:
                value = float(obj.replace(thousand_sep, ""))
            else:
                value = float(obj.replace(thousand_sep, "").replace(decimal_sep, "."))
            if return_type.lower() == 'b':
                return True
            else:
                return value
        else:
            value = float(obj)
            if return_type.lower() == 'b':
                return True
            else:
                return value
    except ValueError:
        return False
        if return_type.lower() == 'b':
            return False
        else:
            return None

我可能会把逻辑分开。。。我想这正是你想要做的

def get_non_base_10(s):
    #support for base 2,8,and 16
    if s.startswith("O") and s[1:].isdigit():
       return int(s[1:],8)
    elif s.startswith("0x") and s[2:].isdigit():
       return int(s[2:],16)
    elif s.startswith("0b") and s[2:].isdigit():
         return int(s[2:],2)

def get_number(s,decimal_separator=".",thousands_separator=","):
    if isinstance(s,basestring):
       temp_val = get_non_base_10(s)
       if temp_val is not None:
          return temp_val
       s = s.replace(decimal_separator,".").replace(thousands_separator,"")
    try:
       return float(s)
    except ValueError:
       return "nan"

def is_number(s,decimal_separator=".",thousands_separator=",",return_type="b"):
    numeric = get_number(s,decimal_separator,thousands_separator)
    return numeric if return_type != "b" else numeric != "nan"

我可能会把逻辑分开。。。我想这正是你想要做的

def get_non_base_10(s):
    #support for base 2,8,and 16
    if s.startswith("O") and s[1:].isdigit():
       return int(s[1:],8)
    elif s.startswith("0x") and s[2:].isdigit():
       return int(s[2:],16)
    elif s.startswith("0b") and s[2:].isdigit():
         return int(s[2:],2)

def get_number(s,decimal_separator=".",thousands_separator=","):
    if isinstance(s,basestring):
       temp_val = get_non_base_10(s)
       if temp_val is not None:
          return temp_val
       s = s.replace(decimal_separator,".").replace(thousands_separator,"")
    try:
       return float(s)
    except ValueError:
       return "nan"

def is_number(s,decimal_separator=".",thousands_separator=",",return_type="b"):
    numeric = get_number(s,decimal_separator,thousands_separator)
    return numeric if return_type != "b" else numeric != "nan"

使用正则表达式,您可以执行以下操作:

import re
regex = re.compile( r'[+-]{0,1}\d{1,3}(,\d\d\d)*(\.\d+)*'
现在,如果您有字符串txt,请执行以下操作

regex.sub( '', txt, count=1 )
如果字符串是一个数字,则会以空字符串结尾,分隔符为千和。作为十进制分隔符

此方法强制使用严格的3位数千分位分隔符。例如200001.43不是一个数字,因为千位分隔符是错误的。1220001.43也不是一个数字,因为它缺少一个


使用正则表达式,您可以执行以下操作:

import re
regex = re.compile( r'[+-]{0,1}\d{1,3}(,\d\d\d)*(\.\d+)*'
现在,如果您有字符串txt,请执行以下操作

regex.sub( '', txt, count=1 )
如果字符串是一个数字,则会以空字符串结尾,分隔符为千和。作为十进制分隔符

此方法强制使用严格的3位数千分位分隔符。例如200001.43不是一个数字,因为千位分隔符是错误的。1220001.43也不是一个数字,因为它缺少一个


@弗拉瑟格雷厄姆不是复制品。这篇文章需要更多的功能来容纳不同的千位和十进制分隔符;而是测试给定的字符串是否可以解释为数字。可以有更多的格式,例如十六进制或指数形式。如果你的头衔能更准确地反映你正在解决的问题,那就太好了。@FraserGraham不是重复的。这篇文章需要更多的功能来容纳不同的千位和十进制分隔符;而是测试给定的字符串是否可以解释为数字。可以有更多的格式,例如十六进制或指数形式。如果你的标题能更准确地反映你正在解决的问题,那就太好了。很好的正则表达式!:虽然你不应该做[+-]{0,1}吗?@JoranBeasley谢谢,修正了那个漂亮的正则表达式虽然你不应该做[+-]{0,1}吗?@JoranBeasley谢谢,修正了我从来没有想到如果其他模式可以工作的话返回。谢谢你,你把它带到了其他的基数系统。谢谢,因为它确实消除了重复。我从来没有想到如果其他模式可以工作返回。谢谢你,你把它带到了其他的基数系统。谢谢,因为它确实消除了重复。