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()
As a guess:
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.split() on the string."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.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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With