Python程序不应该计算浮点长度,而应该计算字符串



我正在Python中创建一个函数来计算字符串的长度,同时让用户知道Int和float不是字符串。Int 部分有效,但该功能不尊重浮点数,我不知道为什么。

我在Windows 10中使用Visual Studio Code。 Python 3.7.0 [MSC v.1914 64 bit (AMD64(] on win32

def length_string(mystring):
try:
if type(int(mystring)) == int:
return f"Hello, this is not {mystring} a string"
elif type(mystring) == float:
return f"Hello, this is not {mystring} a string"
elif type(str(mystring)) == str:
return len(mystring)
except:
return len(mystring)

string_name = 输入("请输入您的值:"( 打印(length_string(string_name(('

结果字符串 hello 是:5 结果 Int 555 = 您好,这不是 555 字符串 结果浮点数 555.0 = 5,但应与 int 相同。

Float 在第一个 if 块中引发值错误。由于仅当变量为字符串时才返回长度,因此可以通过单个比较更有效地执行此操作。

def length_string(mystring):
if isinstance(mystring, basestring):
return len(mystring);
else:
return f"Hello, {mystring} is not a string";

如果字符串int(mystring)转换成功,则类型始终为字符串,否则执行execpt-block,因此两个elif块永远不会被执行。

def length_string(mystring):
try:
float(mystring)
except ValueError:
return f"Hello, this is not {mystring} a string"
return len(mystring)

最新更新