python - 输入命令将输入​​作为 int 而不是 Python 中的 str

标签 python

我是一名使用 Python 2.79 编程的初学者。我正在编写一个程序,“标记”一个数学公式,基本上将每个数字和运算符转换为列表中的一个项目。

我的问题目前在我的输入命令中(因为这是一个语义错误,我还无法测试其余的代码)。我要求用户输入一个数学方程。 Python 将此解释为 int。

我尝试将它变成一个字符串,Python 基本上解决了这个公式,并通过我的 tokenize 函数运行了解决方案

我的代码如下:

#Turn a math formula into tokens

def token(s):
    #Strip out the white space
    s.replace(' ', '')
    token_list = []
    i = 0
    #Create tokens
    while i < len(s):
        #tokenize the operators
        if s[i] in '*/\^':
            token_list.append(s[i])
        #Determine if operator of negation, and tokenize
        elif s[i] in '+-':
            if i > 0 and s[i - 1].isdigit() or s[i - 1] == ')':
                token_list.append(s[i])
            else:
                num = s[i]
                i += 1
                while i < len(s) and s[i].isdigit():
                    num += s[i]
                    i += 1
                token_list.append(num)
        elif s[i].isdigit():
            num = ''
            while i < len(s) and s[i].isdigit():
                num += s[i]
                i += 1
            token_list.append(num)
        else:
            return []
    return token_list

def main():
    s = str(input('Enter a math equation: '))
    result = token(s)
    print(result)

main()

如有任何帮助,我们将不胜感激

我正在寻找

最佳答案

Python 将用户的输入解释为整数的原因是 input('Enter a mathequation: ') 行。 Python 将其解释为 eval(raw_input(prompt))raw_input 函数根据用户输入创建一个字符串,并且 eval 评估该输入 - 因此 5+2 的输入被视为 “5+2” by raw_inputeval 将其计算为 7

Documentation

关于python - 输入命令将输入​​作为 int 而不是 Python 中的 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33306145/

相关文章:

python - scrapy - 如何用 Pandas 数据框中的数据填充项目?

python - 什么轻量级 python 库,用于简单的 3D 科学可视化

python - 从 python 使用 nmap 时如何启用 "no ping"

python - 尝试 MNIST 数据集时,tensorflow 和 matplotlib 包出现问题

python - 在没有 for 循环的情况下获取到 1D/2D 中每个最近元素的距离

python - 构建包含可变大小小部件的 QT Designer 布局

python - Python中Enum和IntEnum之间的区别

python - CPython 和 IronPython 的功能差异

python - 指定坐标处的PyQt无框窗口

python - Azure Functions Blob 部署