允许字符串变为设置值的变量

时间:2017-01-04 15:58:48

标签: python

并提前感谢。我正在研究一个程序,在此期间,我允许更改程序本身内的一些连接。因此,我编写了以下代码来促进这一点:

n = {'car': 'gate'} #this also exists for all the other directions
directions = ['n', 's', 'e', 'w', 'ne', 'nw', 'sw', 'se', 'u', 'd'] 
roomto = input("\nROOM TO CHANGE CONNECTIONS FOR (A) # ").lower()
toroom = input("\nROOM IT SHOULD LEAD TO (B) #").lower()   
toroomd = input("\nWHAT DIRECTION SHOULD LEAD FROM A TO B? # ").lower()
toroomb = input("\nWHAT DIRECTION SHOULD LEAD FROM B TO A? # ").lower()
if(toroomd in directions) and (toroomb in directions):
   statusd = 'status' + toroomd
   statusb = 'status' + toroomb
   toroomd[roomto] = toroomd
   toroomb[toroom] = roomto
   print("Success!")

然而,它给了我以下错误(忽略行号,它就是它在大型程序中的位置):

TrTraceback (most recent call last):
File "python", line 1885, in <module>
TypeError: 'str' object does not support item assignment

我已经阅读了一下,并尝试将toroomd [roomto] = toroomd包装在一个列表中,但这只是给了我一个关于列表不能围绕str并且必须围绕浮点或拼接的新错误。

有任何建议,或者这是不可能的?

1 个答案:

答案 0 :(得分:1)

python中的字符串是不可变的 你无法改变它 只创建一个新的。

toroomd[roomto] = toroomd
必须是 toroomd = toroomd[:roomto] + toroomd + toroomd[roomto+1:]