最近在寫代碼的時候,發現一個問題,想判斷一個字符串是不是一個合法的小數,發現字符串沒有內置判斷小數的方法,然后就寫了一個判斷字符串是否是小數,可以判斷正負小數,代碼如下:
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'))
|