Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a string in a function when calling a function?

I'm not sure if this is possible but is there a way to change a string that a function prints while calling it from another function? I want to do something like this:

def string():
    print ("This cat was scared.")

def main():
    for words in string():
        str.replace("cat", "dog")
        # Print "The do was scared."

main()
like image 426
Kade Williams Avatar asked Mar 13 '26 16:03

Kade Williams


1 Answers

As a guess:

  • You wanted string() to return a value the caller can use, instead of just printing something to the screen. So you need a return statement instead of a print call.
  • You want to loop over all of the words in that returned string, not all the characters, so you need to call split() on the string.
  • You want to replace stuff in each word, not in the literal "cat". So, you need to call replace on word, not on the str class. Also, replace doesn't actually change the word, it returns a new one, which you have to remember.
  • You want to print out each of those words.

If so:

def string():
    return "This cat was scared."

def main():
    for word in string().split():
        word = word.replace("cat", "dog")
        print(word, end=' ')
    print()

main()

That fixes all of your problems. However, it can be simplified, because you don't really need word.replace here. You're swapping out the entire word, so you can just do this:

def main():
    for word in string().split():
        if word == "cat": word = "dog"
        print(word, end=' ')
    print()

But, even more simply, you can just call replace on the entire string, and you don't need a loop at all:

def main():
    print(string().replace("cat", "dog"))
like image 118
abarnert Avatar answered Mar 15 '26 06:03

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!