Thi*_*Axe 3 python function python-3.x
你好,我是 python 新手,我想知道是否可以创建一个只接受某些类型的值的函数,在本例中是字符串,否则错误
parameter that needs to be string
|
v
def isfloat(a):
if a.count('.') > 1:
return False
for c in a:
if c.isnumeric() or c == '.':
v = True
else:
return False
return v
Run Code Online (Sandbox Code Playgroud)
在 Python 3.5+ 中,您可以使用类型来注释您的函数:
def isfloat(a: str):
# More code here...
Run Code Online (Sandbox Code Playgroud)
但类型注释实际上并不检查类型!
因此,最好使用断言语句添加健壮的类型检查:
def isfloat(a: str):
assert isinstance(a, str), 'Strings only!'
# More code here...
Run Code Online (Sandbox Code Playgroud)
如果不是字符串,您的函数assert将引发。AssertationErrora