【问题标题】:Recognising an input() as either a str, float, or int and acting accordingly将 input() 识别为 str、float 或 int 并采取相应措施
【发布时间】:2017-03-04 06:17:45
【问题描述】:

这里是 Python 初学者。我正在编写一个使用无限循环并允许用户输入关键术语来访问不同“工具”或“模块”的程序。

在这些“模块”之一中,用户可以输入一个值并将其转换为二进制。我想:

  1. 允许程序识别值是 int 还是 浮动,然后运行将值转换为二进制的代码
  2. 允许程序识别输入的值是否为 str 并且 str 表示“返回”,此时将退出当前循环。

据我所知,这个问题正在发生,因为 input() 会自动将输入的内容转换为 str (由于:http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html“首先它会打印您作为参数提供的字符串”)。

如何让下面的代码识别输入是 str、float 还是 int,然后执行相关的 if 语句?目前,我的这部分代码可以接受“返回”以退出循环,但会将任何 int 或 float 值作为 str,使程序提示用户再次输入十进制值。

    #decimal to binary   
    while search == "d2b":
        dec2bin = input("\nDecimal Value: ")
        if type(dec2bin) == int:
            print("Binary Value: " + "{0:b}".format(dec2bin))
        elif type (dec2bin) == str:
            if dec2bin == "back":
                search = 0
        elif type (dec2bin) == float:
                #code for float to binary goes here

编辑:与此线程 (Python: Analyzing input to see if its an integer, float, or string) 不同,因为在 input() 上使用了列表 E2:似乎无法使用建议的副本作为问题的解决方案。但是,Francisco 在此线程中的评论有解决方案

【问题讨论】:

  • 标记为重复的问题不是真的。这就是如何在列表中找到对象的类型——而不是字符串可以转换成的类型。

标签: python python-3.x


【解决方案1】:

使用例外! intfloat 函数在无法转换传递的值时会抛出 ValueError 异常。

while search == "d2b":
    dec2bin = input("\nDecimal Value: ")
    try:
        dec2bin = int(dec2bin)
    except ValueError:
        pass
    else:
        print("Binary Value: " + "{0:b}".format(dec2bin))
        continue

    try:
        dec2bin = float(dec2bin)
    except ValueError:
        pass
    else:
        #code for float to binary goes here
        continue

    if dec2bin == "back":
        search = 0

尝试转换的顺序很重要,因为传递给int 的每个值都对float 有效,而传递给float 的每个值都可以有效传递给str

【讨论】:

  • 这似乎在我的代码中正常工作,谢谢。如果您不介意 - 可以将浮点数以类似于整数的方式格式化为二进制吗?我现在正在用我所知道的有关格式化和获取错误的知识进行一些试验。
  • @CharlieWebb 取决于您将float 转换为二进制的意思,也许this 会回答您的问题。
  • 因此,目前代码将整数格式化为二进制: dec2bin = input("\nDecimal Value: ") try: dec2bin = int(dec2bin) except ValueError: pass else: print("Binary Value: " + "{0:b}".format(dec2bin)) continue 在代码的 float 部分的末尾是否有类似的可能?我需要将浮点数转换为 str 或 int 吗?就我自己的 python 知识而言,阅读您链接的线程目前有点不行-我不理解回复中的大部分代码。
【解决方案2】:

您可以使用str.isalpha()str.isdigit() 来实现此目的。因此您的代码将是:

while search == "d2b":
    dec2bin = input("\nDecimal Value: ")
    if dec2bin.lstrip("-").isdigit():
        print("Binary Value: " + "{0:b}".format(int(dec2bin))) # OR, simply bin(int(dec2bin))
    elif dec2bin.isalpha():  # OR, isalnum() based on the requirement
        if dec2bin == "back":
            search = 0
    else:
        try:
            _ = float(dec2bin)
        except:
            pass
        else:
            #code for float to binary goes here

这里,我使用str.lstrip() 从字符串的开头删除-,因为.isdigit() 无法检查负数字符串。

有关str 对象可用方法的完整列表,请参阅Python 3: String Methods

【讨论】:

  • 你可以有一个负数
  • @PadraicCunningham:更新了答案。感谢您的关注。
  • 我没有选票,所以不能 +1,你也可能想看看 isdecimal 的作用;)
  • @PadraicCunningham:我会的。但是我现在使用的机器没有安装 Python 3。如果我做错了什么,请随时编辑答案。
  • 好的。我现在在另一台机器上。你说的对。用 traditional try/except 更新了答案
【解决方案3】:

使用ast.literal_eval()你可以做类似的操作。这是将input()str转换为 strfloatint的示例代码。

import ast  
def input_conv(strr):
   try:
      base = ast.literal_eval(strr)
      return base
   except:
      return strr

>>> b = input()
hi
>>> input_conv(b)
'hi'
>>> type(input_conv(b))
<class 'str'>
>>> b = input()
1
>>> type(input_conv(b))
<class 'int'>
>>> b = input()
1.222
>>> type(input_conv(b))
<class 'float'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多