7/15: Reason the code isn't running?


Why is this code showing “‘str’ object does not support item assignment” error?

def reverse(text):
  for i in range(len(text)/2):
  return text  


lists are mutable, so we can change a value in a list:

my_list = ['a', 'b', 'c']
my_list[2] = 'd'
print my_list

strings on the other hand are immutable, they can not be changed. So item assignment (like i did above) is not supported for strings, which you seem to attempt twice (text[]=), which won’t work


right…so if I convert the string into a list, use my method, and then convert it back to string it should work right?

Like strings can be cnverted to lists:

for i in "string":

but can the reverse be done?


But why would you do that? That sounds like additional steps:

  1. convert to list, using append
  2. reverse the string
  3. join list into string

then step 1 and 2 could just be merged, appending to list in reverse (or loop in reverse and append to list)


Using this?

print "".join(list)

yeah i just realised that…
i think i confused strings in python with arrays in c++.
Thanks a lot!


yep :slight_smile:

lists are more like arrays then strings are, c++ has strings as well


Strings are immutable objects, unlike lists which support item assignment. We cannot change characters or assign characters to a position in the string.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.