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


#1

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

def reverse(text):
  for i in range(len(text)/2):
    t=text[i]
    text[i]=text[(len(text)-i)-1]
    text[(len(text)-i)-1]=t
  return text  
  

#2

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


#3

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:

lists=[]
for i in "string":
 lists.append(string[i])

but can the reverse be done?


#4

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)


#5

Using this?

print "".join(list)

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


#6

yep :slight_smile:

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


#8

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


#9

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