【问题标题】:Function to detect integers instead string in Python [duplicate]在Python中检测整数而不是字符串的函数[重复]
【发布时间】:2021-11-14 07:51:57
【问题描述】:

我正在尝试创建一个函数来计算字符串中的字符数并检测何时键入整数,条件是使用“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() 总是返回一个字符串

标签: python string integer


【解决方案1】:

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

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

【讨论】:

  • 非常感谢您的帮助。我的代码现在可以工作了。
猜你喜欢
  • 2016-05-03
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2016-02-18
相关资源
最近更新 更多