使用条件的字符串长度(使用Python)

2024-05-23 16:12:50 发布

您现在位置: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

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

提前谢谢


Tags: the字符串代码pystringreturntype整数
2条回答

你的意思是要有一个函数为你尝试这些类型吗

def tryTypes(word):
    try:
        print(string_length(int(word)))
        return
    except ValueError as e:
        pass

    try:
        print(string_length(float(word)))
        return
    except ValueError as e:
        pass

    print(string_length(word))

word = input("Enter the string: ")
tryTypes(word)

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

相关问题 更多 >