天天看点

python判断一个字符串是否是小数

最近在写代码的时候,发现一个问题,想判断一个字符串是不是一个合法的小数,发现字符串没有内置判断小数的方法,然后就写了一个判断字符串是否是小数,可以判断正负小数,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<pre class="prettyprint lang-py">def is_float(s):

        s = str(s)

        if s.count('.')==1:#判断小数点个数

            sl = s.split('.')#按照小数点进行分割

            left = sl[0]#小数点前面的

            right = sl[1]#小数点后面的

            if left.startswith('-') and left.count('-')==1 and right.isdigit():

                lleft = left.split('-')[1]#按照-分割,然后取负号后面的数字

                if lleft.isdigit():

                    return True

            elif left.isdigit() and right.isdigit():

                #判断是否为正小数

                return True

        return False

print(is_float('-98.9'))