Home > OS >  Inability to change string
Inability to change string

Time:04-09

I am trying to solve a maze question.

maze = [
"#o######",
"# ##   #",
"# ## # #",
"#    # #",
"## ### #",
"##  ## #",
"######e#",
]

maze[0][1] = "#"

Output:

TypeError: 'str' object does not support item assignment

I thought of an algorithm that works with the logic of filling the space behind me with a "#" every time I move forward. But I learned that strings are immutable.

Is there anything in Python that allows me to run this algorithm in another way?

CodePudding user response:

You can only access specific char from string using its index, but you cannot change it. You have to recreate it, eg. to change first digit of string:

text = 'abcdef'
text = 'X'   text[1:] # changes first letter to X and adds rest of the string
> 'Xbcdef'

Or more general example:

def change(text, char, index):
    return text[:index]   char   text[(index 1):]

text = 'abcdef'
text = change(text, 'X', 2)
> 'abXdef'

So i your maze case:

maze = [
"#o######",
"# ##   #",
"# ## # #",
"#    # #",
"## ### #",
"##  ## #",
"######e#",
]

maze[0] = change(maze[0], '#', 1)

CodePudding user response:

You can change the list of strings to a list of lists by doing

maze = [list(s) for s in maze] #list comprehension

or more verbosely

for i in range(len(maze)):
    maze[i] = list(maze[i])

Then you can do things like maze[0][1] = "#".

If you want it back in string form, do

maze = ["".join(lst) for lst in maze]

or

for i in range(len(maze)):
    maze[i] = "".join(maze[i])

CodePudding user response:

You can use replace method instead.

maze = [
"#o######",
"# ##   #",
"# ## # #",
"#    # #",
"## ### #",
"##  ## #",
"######e#",
]
for i in maze:
    j = i.replace("o","#")
    print(j)
  • Related