Reputation: 839
I'm trying to add to a string over a few function calls that you could basically say will "update" the string. So for example, if you had:
'This is a string'
You could change it to:
'This is my string'
Or then:
'This is my string here'
etc..
My data for the string is coming from a nested dictionary, and I made a function that will change it to a string. This function is called 'create_string()'. I won't post it because it is working fine (although if necessary, I'll make an edit. But take my word for it that it's working fine).
Here's the function 'updater()' which takes three arguments: The string, the position you want to change and the string you want to insert.
def updater(c_string, val, position):
data = c_string.split(' ')
data[position] = str(val)
string = ' '.join(data)
return string
x = create_string(....)
new_string = updater(x,'hey', 0)
Which up until this point works fine:
'hey This is a string'
But when you add another function call, it doesn't keep track of the old string:
new_string = updater(x,'hey',0)
new_string = updater(x,'hi',2)
> 'This is hi string'
I know that the reason is likely because of the variable assignment, but i tried just simply calling the functions, and I still had no luck.
How can I get this working?
Thanks for the help!
Note: Please don't waste your time on the create_string() function, it's working fine. It's only the updater() function and maybe even just the function calls that I think are the problem.
**Edit:**Here's what the expected output would look like:
new_string = updater(x,'hey',0)
new_string = updater(x,'hi',2)
> 'hey is hi string'
Upvotes: 0
Views: 68
Reputation: 235984
You need to do this, to keep modifying the string:
new_string = updater(x, 'hey', 0)
new_string = updater(new_string, 'hi', 2)
x
is the same after the first call, the new modified string is new_string
from that point on.
Upvotes: 4
Reputation: 16005
You store the result of updater
to new_string
, but don't pass that new_string
to the next updater
call.
Upvotes: 3