How do you change a letter in a string?


Hello, I'm doing "7. Reverse".

My attempt to do this involves changing the strings' letters, like this:

text = "hello"
text[0] = "a"

but this doesn't work. What would be the best way to do this?

My current code looks like this, which doesn't work for the above reason.

def reverse(text):
    new = text
    for i in range(len(text)-1):
        new[i] = text[len(text)-1-i]
    print new

Edit: I think I have to put "text" in a list variable instead of a string, right? I'll try it out.


Yes, you'll want to use a list and then .join() for this exercise.


Can you remind me how it's done? I can't remember


Why does it not exist? If new = text then in the word "Hello" new[0] will be H


yeah you're right.. sorry, error..


The string Value is assigned to the variable text
The string Value itself is immutable... cannot be changed

def reverse(text):
    new = ""
    for i in text:
        new = i + new
    print new
    new = ""
    for i in range(len(text)-1):
        new = text[i] + new
    print new


But they want you to use the split() Method followed by a join() Method


Strings are in a class of objects that are immutable (in theory, anyway). If we treat them this way then we don't get lured into thinking that we can change them, even if, as in Python (and JavaScript) we can.

The way we get around this is by iterating over the original and build a temporary string that incorporates the change. We can then overwrite the original. This is a change by redefining, rather than by mutating.

Not necessary. A string is already an iterable. Just iterate the string. Since we already determined that changing the string is not an option, making a copy of the string is not the approach to use. And when we think of it, building a string goes against the mutation rule. That leaves a list as the temporary object.

new = []

Given that we are only reading the original string, we can use a look-up (item) rather than a range (index).

for char in text:
    new.insert(0, char)
return ''.join(new)

>>> revers("Take the long way home")
'emoh yaw gnol eht ekaT'


What is the '' in ''.join(new)?

EDIT: I guess it's an empty string which has "new" added into it, right?



This is what the list looks like before we join it...

['e', 'm', 'o', 'h', ' ', 'y', 'a', 'w', ' ', 'g', 'n', 'o', 'l', ' ', 'e', 'h', 't', ' ', 'e', 'k', 'a', 'T']


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