如何在Python中评估字符串?

时间:2018-01-11 14:49:23

标签: python eval

这是我的代码:

from decimal import *
a = eval (input ("Pelase, give me a numbre: \n"))
if type(a) not in (int, float, Decimal):
    print ("It's not possible to make a float from a complex number")
else :
    a=float(a)
    print ("Now your number is", a, "and its type is" , type(a))

如果输入只是文本(例如Hello),则会出错。

我想评估它是否为str,并根据该评估向用户提供建议。

6 个答案:

答案 0 :(得分:3)

def do_input():
    user_input = input("Input a number: ")
    try:
        num = int(user_input)
    except ValueError:
        try:
            num = float(user_input)
        except ValueError:
            print("You didn't input a number")
            num = None
    return num

for _ in range(3):
    a = do_input()
    print("Now your number is", a, "and its type is" , type(a))

输出:

Input a number: 3
Now your number is 3 and its type is <class 'int'>
Input a number: 2.1
Now your number is 2.1 and its type is <class 'float'>
Input a number: ij
You didn't input a number
Now your number is None and its type is <class 'NoneType'>

答案 1 :(得分:1)

在python中,字符串就像是“类str的实例”。为了比较输入中的“内容”是否为字符串,您可以制作类似......

的内容
a = input("Put something...")

if isinstance(a, str):
    print("Error caught, a string was given...")
else:
    print ("Now your number is", a, "and its type is" , type(a))

答案 2 :(得分:1)

eval函数并没有真正解析给定的字符串作为数字。它evaluates string as a python expression。所以尝试下面提到的两种方法之一:

单程

from decimal import *

a = input("Please, give me a number : \n")
if type(a) not in (int, float, Decimal):
    print("It's not possible to make a float.")
else:
    a = float(a)
    print("Now your number is", a, "and its type is", type(a))

案例1:

Please, give me a number : 
5
Now your number is 5.0 and its type is <class 'float'>

案例2:

Please, give me a number : 
hello
It's not possible to make a float.

另一种方式

try:
    a = float(input("Please, give me a number : \n"))
    print("Now your number is", a, "and its type is", type(a))
except ValueError:
    print("It's not possible to make a float.")

案例1:

Please, give me a number : 
5
Now your number is 5.0 and its type is <class 'float'>

案例2:

Please, give me a number : 
hello
It's not possible to make a float.
  

表达式参数被解析并作为Python表达式进行求值   (技术上讲,条件列表)使用全局变量和本地变量   字典作为全局和本地命名空间。如果是全局字典   存在且缺少'内置',当前全局变量被复制   在解析表达式之前进入全局变量。这意味着表达   通常可以完全访问标准的内置模块和   传播受限制的环境。如果是本地词典   省略它默认为全局字典。如果两个字典   省略,表达式在环境中执行   调用eval()。返回值是评估的结果   表达。语法错误报告为异常。例如:

from math import *

def secret_function():
    return "Secret key is 1234"

def function_creator():

    # expression to be evaluated
    expr = raw_input("Enter the function(in terms of x):")

    # variable used in expression
    x = int(raw_input("Enter the value of x:"))

    # evaluating expression
    y = eval(expr)

    # printing evaluated result
    print("y = {}".format(y))

if __name__ == "__main__":
    function_creator()
     

输出:

Enter the function(in terms of x):x*(x+1)*(x+2)
Enter the value of x:3
y = 60

答案 3 :(得分:0)

而不是使用eval(这是相当危险的 - 用户可以输入任何有效的python代码并且它将运行),你应该使用int,并使用try-catch语句以下内容:

while True:
    try:
            a = int(input ("Pelase, give me a numbre: \n"))
            break
    except ValueError:
            print("Not a number!")

有关更多示例,请参阅此处:https://docs.python.org/3/tutorial/errors.html

答案 4 :(得分:0)

eval函数并没有真正解析给定的字符串作为数字。它evaluates string as a python expression

因此eval('2')给出2的事实只是一个巧合,因为2是正确的python表达式,其计算结果为数字。

所以你不应该使用eval来将字符串解析为数字。相反,只需尝试将其解析(转换)为整数,浮点数和十进制(按此顺序),如果您在任何尝试中都没有收到错误,则表示这是指定类型的正确数量。

@ jose-a发布的答案显示了如何做到这一点。

答案 5 :(得分:0)

为什么不简单地将您的逻辑封装在try :: except块中,如下所示:

iNumber = input ("Please, enter a Number: \n")
try :
    # TRY CASTING THE ENTERED DATA TO A FLOAT...
    iNumber = float(iNumber)
    print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber)))
except:
    # IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO... 
    # DO SOMETHING - THROW AN EXCEPTION OR WHATEVER...
    print ("Non Numeric Data is not acceptable...")



更新:
如果你想处理复数输入(就像你在评论中提到的那样)......你可以将上面的代码包装在if - else块中,如下所示:

import re

iNumber         = input ("Please, enter a Number: \n")
# MATCH A SOMEWHAT COMPLEX NUMBER PATTERN
if re.match(r"\d{1,}[ \-\+]*\d{1,}[a-z]", iNumber):
    print("Not possible to convert a complex number to float: {}".format(iNumber))
else:
    try :
        # TRY CASTING THE ENTERED DATA TO A FLOAT...
        iNumber = float(iNumber)
        print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber)))
    except:
        # IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO...
        # DO SOMETHING - THROW AN EXCEPTION OR WHATEVER...
        print ("Non Numeric Data is not acceptable...")