Reputation: 63
Is it possible to empty a string using functions in python?
For example:
otherText="hello"
def foo(text):
text=""
foo(otherText)
print(otherText)
prints
hello
instead of an empty string. Is there a way to empty the string without assigning it a return value or using global variables?
Upvotes: 2
Views: 5026
Reputation: 255005
It's not possible. There are 2 reasons for that
Python strings are immutable
Python implements a so called "call by sharing" evaluation strategy:
The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller
Upvotes: 4
Reputation: 3315
As noted by zerkms, it is strictly not possible, python does not pass argument by reference.
There are a few tricks that can be used as workarounds, such as passing a list or object, containing your string.
otherText=["hello"]
def foo(text):
text[0]="Goodbye string"
foo(otherText)
print(otherText) //Goodbye string
Upvotes: 2