2017-04-14 53 views
-1

我一直在试图编写一个程序,它可以找到输入数学函数的根。我刚刚开始,所以我在这里展示的仅仅是开始,并且还有未使用的变量。与.join函数的陌生人错误

这里我写这应该更换期限与价值,你输入,比方说,100以下的函数“X”的功能代码:

code = list(input("Enter mathematical function: ")) 
lowBound = int(input("Enter lower bound: ")) 
upBound = int(input("Enter upper bound: ")) 

def plugin(myList, value): 
    for i in range(len(myList)): 
    if myList[i] == 'x': 
     myList[i] = value #replaces x with the inputted value 
    return ''.join(myList) #supposed to turn the list of characters back into a string 

print(plugin(code,upBound)) 

但是当我运行该程序,我得到的错误:

Traceback (most recent call last): 
File "python", line 11, in <module> 
File "python", line 9, in plugin 
TypeError: sequence item 0: expected str instance, int found 

(我使用的在线编程平台,因此该文件就被称为“蟒蛇”)

这没有任何意义,我。 myList不应该是一个int,即使它是正确的数据类型(str),它应该是一个列表。有人可以解释这里发生了什么吗?

+3

'upBound'是一个整数,你把它放到列表中。你不能使用'str.join()'来加入字符串值以外的任何东西。 –

回答

1

您正在用int类型替换str类型(或字符)。

试试这个:

myList[i] = str(value) 
0

只能加入串

return ''.join(str(x) for x in myList) 

或者,更简洁的迭代。删除功能

print(''.join(str(upBound if x =='x' else x) for x in code)