0

I want to change the first element of a string with the last element.

def change(string):
    for i in range(16):
        helper = string[i]
        string[i]=string[15-i]
        string[15-i]=helper
    return string
print (change("abcdefghijklmnop"))

Error Output:

string[i]=helper2[0]
TypeError: 'str' object does not support item assignment
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
the_new_one
  • 33
  • 1
  • 5

3 Answers3

1

You can't alter a string; they're immutable. You can create a new string that is altered as you want:

def change(string):
    return string[-1]+string[1:-1]+string[0]
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

You can use "*" operator.

my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]

Read here for more information.

aghd
  • 685
  • 2
  • 9
  • 20
0

As you discovered, strings are immutable so you can index a string (eg string[x]), but you can't assign to an index (eg string[x] = 'z').

If you want to swap the first and last element, you will need to create a new string. For example:

def change(input_str):
  return input_str[-1] + input_str[1:-1] + input_str[0]

However, based on your example code, it looks like you trying to swap all the "elements" of the string. If you want to do that, see this previous discussion on different methods of reversing a string: Reverse a string in Python

Additionally, even if you could "index" a string, your code would not work as written. With a minor change to "explode" it into a list:

def change(string):
    string = [c for c in string]
    for i in range(16):
        helper = string[i]
        string[i]=string[15-i]
        string[15-i]=helper
    return string
print (change("abcdefghijklmnop"))

DEMO

As you can see, the output is the "same" as the input (except exploded into a list) because you step through every index in the string, reverse all of them twice (which puts them back in their original position).

Community
  • 1
  • 1
lsowen
  • 3,728
  • 1
  • 21
  • 23