-1
def modify(text):
    text = text[:1] + 'Z' + text[2:]
    return

text = 'abcdefg'
modify(text)
print text

This does not change the string. What is the best way to make such changes?

2 Answers2

2

Strings are immutable, you can't change them in a function and see the change outside the function.

The proper way to do this is to return the modified string and reassign it where it was called.

def modify(text):
    text = text[:1] + 'Z' + text[2:]
    return text

text = 'abcdefg'
text = modify(text)
print text
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • I dont' think this is about immutable strings. I think the issue is that the OP thinks that assignment to a name that has been passed as an argument affects the calling scope. You offer the correct solution, but the incorrect diagnosis. – Steven Rumbalski Dec 08 '15 at 16:44
  • @StevenRumbalski in that case they should check out http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference – Mark Ransom Dec 08 '15 at 16:46
  • Yes, that addresses it perfectly. Matter of fact, I'm closing this question in favor of that one. – Steven Rumbalski Dec 08 '15 at 16:47
1

You must return the modified text from your modify function, otherwise, your modification won't take any effect:

def modify(text):
    text = text[:1] + 'Z' + text[2:]
    return text

And since text inside modify function is a local variable, the modification won't affect the global text variable (which you passed to modify function) until you assign it:

text = modify(text)

Iron Fist
  • 10,739
  • 2
  • 18
  • 34