在 Python 中检测整数而不是字符串的函数

Function to detect integers instead string in Python

我正在尝试制作一个函数来计算字符串中的字符数并检测何时键入整数,条件是使用“if”函数。我希望如果我输入任何整数,如“4464468”而不是字符串,程序会显示:“对不起,你输入了一个整数”。但是,相反,计算总数并显示“您键入的单词有 7 个字符”。

下一个是我的代码:

def string_lenght(mystring):
       return len(mystring)`

#Main Program

mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
        print("Sorry, you typed an integer")

else:
        print("The word you typed has",string_lenght(mystring), "characters")

我是 Python 的新手。非常感谢您的帮助和耐心等待。

此致。

input()总是returns一个字符串所以你可以尝试将它转换成int/float,如果操作成功则它是一个数字,否则它是一个字符串:

try:
    float(mystring)
    print("Sorry you typed an integer")
except ValueError:
    # Rest of the code ...