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

时间:2015-10-23 15:28:13

标签: 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()

任何帮助将不胜感激

我期待

1 个答案:

答案 0 :(得分:1)

Python将用户的输入解释为整数的原因是由于行input('Enter a math equation: ')。 Python将其解释为eval(raw_input(prompt))raw_input函数从用户输入创建一个字符串,eval评估该输入 - 因此5+2的输入被"5+2"视为raw_input,并且eval评估为7

Documentation