TARGET= 'i love artifical intelegence'
c='gdfhug'
import random
c[2]=random.choice(TARGET)
print(c)
This code reports this error:
'str' object does not support item assignment
How can I resolve it?
TARGET= 'i love artifical intelegence'
c='gdfhug'
import random
c[2]=random.choice(TARGET)
print(c)
This code reports this error:
'str' object does not support item assignment
How can I resolve it?
Strings are immutable, so they can't be treated exactly like lists/arrays. Thus, when you try and assign a value to the index position 2
, Python stops you.
TARGET= 'i love artifical intelegence'
my_str='gdfhug'
ls = [c for c in my_str] // Convert to a list
ls[2] = random.choice(TARGET) // Reassign a position in the list
print(''.join(ls)) // Convert list back to string and print
The [c for c in my_str]
is a list comprehension that will convert the string to a list. You could also use list(my_str)
. Once you are dealing with the list ls
, your subscription ls[2]
will work as expected. ''.join()
is a function on the empty string ''
that will take each element of ls
and join them together with the empty string. This has the effect of creating a string from the elements of the list, since the joining element is empty.
A string in Python is immutable, so you cannot edit the string like that as you'd do a list.
True, a string is enumerable like list is; but still does not mean that it is mutable.
What you should probably do is build a new string by enumerating over the string c
.
new_string = ''
for i, letter in enumerate(c):
if i == 2:
new_string += random.choice(TARGET)
else:
new_string += letter
You could cast you str to a list
TARGET= 'i love artifical intelegence'
c='gdfhug'
c=list(c)
import random
c[2]=random.choice(TARGET)
print(''.join(c))
Result:
gdehug
The shortest method is to use enumerate
with list comprehension:
import random
TARGET = 'i love artificial intelligence'
c = 'gdfhug'
c = "".join(random.choice(TARGET) if idx == 2 else s for idx, s in enumerate(c))
print(c)