python - 使用条件的字符串长度(使用 Python)
问题描述
我正在尝试一个代码,在输入字符串时,我们会得到字符串的长度。但是,如果我们输入整数或浮点数据类型,我们会收到“错误数据类型”消息。请在下面找到我的代码:
def string_length(word):
if type(word) == int:
return "This is wrong data type"
elif type(word) == float:
return "Wrong data type again!"
else:
return len(word)
word = input("Enter the string: ")
print(string_length(word))
该程序对于字符串输入运行良好,但是对于整数,它返回的是数字(“字符”)而不是消息的数量。请在输出终端窗口下方找到:
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hellooo
7
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hello there
11
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 123
3
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 12.20
5
你能帮我识别/纠正错误吗?
提前致谢。
解决方案
由于您的输入可以是 int 和 float,您可以使用:
def string_length(input_string):
if input_string.isdigit():
return "Integer"
elif input_string.startswith("-") and input_string.count('-') == 1:
str_ = input_string.replace('-','')
if input_string.replace('-','').isdigit():
return "Integer"
elif input_string.count('.') == 1 and str_.replace('.','').isdigit():
return "Float"
elif input_string.count('.') == 1 and input_string.replace('.','').isdigit():
return "Float"
else:
return len(word)
推荐阅读
- c# - VBA 中使用的 C#/.net DLL
- objective-c - Xcode 10 Swift-ObjC 字典兼容性
- python - 电子邮件的平均响应时间
- python - 按数值对包含数字的名称列表进行排序
- c# - “OpenFileDialog”类不包含“ShowDialog()”和“FileName”的定义
- apache-camel - 如何关联 Camel ExchangeCompletedEvent 和多播/拆分?
- php - 如何将翻译放入 Laravel 表单中的数组中?
- swift - Swift:动画 uilayoutconstraints 和更改 alpha 会导致崩溃
- timezone - ISO8601 与时区和时间跨度
- export-to-csv - 从 Grafana 图表导出 CSV 中的数字格式错误