首页 > 解决方案 > 使用条件的字符串长度(使用 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

你能帮我识别/纠正错误吗?

提前致谢。

标签: pythonpython-3.xtypesconditional-statementsstring-length

解决方案


由于您的输入可以是 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)

推荐阅读