【问题标题】:How to identify operators using isdigit in python?如何在 python 中使用 isdigit 识别运算符?
【发布时间】:2019-05-21 06:07:48
【问题描述】:

我正在编写一个程序来检查用户给出的输入是正数还是负数。

我使用 isdigit 打印“错误的选择/输入”。如果用户输入了一个字符串。

程序运行良好...但是一个负数块无法运行。

每当我给出一个负值时,它都会显示错误的选择,因为 isdigit 检查字符串中的整数而不是符号。

我该如何解决这个问题?

【问题讨论】:

  • 你能举个例子吗?
  • 请分享代码
  • isdigit 不是“这是一个数字”测试。这是一个“这个字符串是由数字字符组成的”测试。它几乎总是错误的工作工具,因为工作通常是检查字符串是否可以被解析为某种格式的数字,而不是检查字符串是否由数字字符组成。

标签: python-3.x


【解决方案1】:

您可以先检查第一个字符,如果它是减号,则仅将isdigit() 应用于字符串的其余部分,即:

# py2/py3 compat
try:
    # py2
    input = raw_input
except NameError:
    # py3
    pass

while True:
    strval = input("please input a number:").strip()
    if strval.startswith("-"):
        op, strval = strval[0], strval[1:]
    else:
        op = "+"
    if not strval.isdigit():
        print("'{}' is not a valid number".format(strval))
        continue
    # now do something with strval and op

但是尝试将strval 传递给int() 会简单得多,如果字符串不是整数的有效表示,它将返回一个整数或引发ValueError

# py2/py3 compat
try:
    # py2
    input = raw_input
except NameError:
    # py3
    pass

while True:
    strval = input("please input a number:")
    try:
        intval = int(strval.strip())
    except ValueError:
        print("'{}' is not a valid number".format(strval))
        continue
   # now do something with intval

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2014-10-02
    • 1970-01-01
    相关资源
    最近更新 更多