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?
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?
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
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)