【问题标题】:'str' object has not attribute 'subs'“str”对象没有属性“subs”
【发布时间】:2016-03-02 03:36:58
【问题描述】:

这是我用 Vim 编写的 Python 代码。每当我运行它时,我都会收到错误'str' object has not attribute 'subs'

from sympy import *
x,a_test,b_test,fa_test,fb_test=symbols('x a_test b_test fa_test fb_test')
expr=raw_input("enter the equation")
print expr
print "hello"
try:
    print "hello"
    inc=0
    a=inc
    fa=expr.subs(x,inc)
    print "hello"
    if(fa<0):
        print "hello"
        inc+=1
        fb=expr.subs(x,inc)
        if(fb<=0):
            while(fb<=0):
                inc+=1
    else:
        print "hello"
        inc+=1
        fb=expr.subs(x,inc)
        if(fb<=0):
            while(fb<=0):
                inc+=1
    b=inc
    print a
    print b
    print fa
    print fb
except Exception,e:
    print e

【问题讨论】:

  • 您希望subs 做什么?这不是str 的方法,expr 是(从raw_input 返回)。
  • 您可能正在寻找str.replace。请注意,替换也必须是 str 类型(而不是为 inc 定义的 int)。
  • 我希望 subs 用“inc”的值代替 x 来代替用户输入的方程。
  • @ArsalanMehmood 请阅读documentation for Python's str object
  • 我刚刚编辑了代码并将 expr.subs 替换为 expr.replace 并将 inc 的数据类型从整数更改为字符串,但它对我不起作用..

标签: python sympy


【解决方案1】:

raw_input的返回值为str;你不能像使用 SymPy expr 一样使用它。你需要先parse它:

from sympy.parsing.sympy_parser import parse_expr
...
expr = parse_expr(raw_input("enter the equation"))

【讨论】:

  • 亲爱的 Seluck ....'NegativeOne' 对象没有属性 'strip'......这是什么意思?
  • 一定和你的表情有关。您输入的方程式是什么?
  • 见下文是我修改后的代码,因为你建议我放置 parse_expr 的东西,我正在输入方程 x**2-x-1
  • 对不起,我在这里粘贴代码时遇到了一些错误,但输入方程是 x**2-x-1
  • 很难将代码作为评论发布;您能否将其作为另一个问题发布,因为这是一个不同的问题?
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2016-09-20
  • 2019-03-25
  • 2017-05-13
  • 2014-04-28
相关资源
最近更新 更多