2

I have a Python list that looks like the below:

list = ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']

I access the letter in the index I want by doing this:

list[y][x]

For example, list[1][10] returns F.

I would like to replace F with a value. Thus changing the string in the list.

I have tried list[y][x] = 'o' but it throws the error:

    self.map[y][x] = 'o'
TypeError: 'str' object does not support item assignment

Can anybody help me out? Thanks.

Nic
  • 37
  • 1
  • 2
  • 4
  • Python strings are immutable, and it can be done in this way. – Marcin Dec 08 '14 at 01:49
  • Possible duplicate of [Change one character in a string?](https://stackoverflow.com/questions/1228299/change-one-character-in-a-string) – tripleee Feb 28 '19 at 04:56

4 Answers4

4

As @Marcin says, Python strings are immutable. If you have a specific character/substring you want to replace, there is string.replace. You can also use lists of characters instead of strings, as described here if you want to support the functionality of changing one particular character.

If you want something like string.replace, but for an index rather than a substring, you can do something like:

def replaceOneCharInString(string, index, newString):
    return string[:index] + newString + string[index+len(newString):]

You would need to do some length checking, though.

Edit: forgot string before the brackets on string[index+len(newString):]. Woops.

Community
  • 1
  • 1
nchen24
  • 502
  • 2
  • 9
2

Since python strings are immutable, they cannot be modified. You need to make new ones. One way is as follows:

tmp_list = list(a_list[1])
tmp_list[10] = 'o' # simulates: list[1][10]='o'
new_str = ''.join(tmp_list)
#Gives |oooooooococooooooooi
# substitute the string in your list
a_list[1] = new_str
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

As marcin says, strings are immutable in Python so you can not assign to individual characters in an existing string. The reason you can index them is that thay are sequences. Thus

for c in "ABCDEF":
    print(c)

Will work, and print each character of the string on a separate line.

To achieve what you want you need to build a new string.For example, here is a brute force approach to replacing a single character of a string

def replace_1(s, index, c)
    return s[:index] + c + s[index+1:]

Which you can use thus:

self.map[y] = replace_1(self.map[y], x, 'o')

This will work because self.map is list, which is mutable by design.

kdopen
  • 8,032
  • 7
  • 44
  • 52
0

Let use L to represent the "list" since list is a function in python

L= ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
L[1]='|oooooooococooooooooi'
print(L)

Unfortunately changing a character from an object (in this case) is not supported. The proper way would be to remove the object and add a new string object.

Output

['|wwwwwwwwadawwwwwwwwi', '|oooooooococooooooooi']
repzero
  • 8,254
  • 2
  • 18
  • 40