esteban
esteban

Reputation: 63

Is it possible to empty a string using functions in python?

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

Answers (2)

zerkms
zerkms

Reputation: 255005

It's not possible. There are 2 reasons for that

  1. Python strings are immutable

  2. 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

visibleman
visibleman

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

Related Questions