Jacob Roff
Jacob Roff
300 Points

deleting variables from strings

if I have a string such as message = "I need to go home now" and I want to delete only the word "home" from that string how would I do that without having to delete the whole string?

1 Answer

Steven Parker
Steven Parker
149,029 Points

Strings are immutable (you can't change them) but you can create a new one that has the word removed from it:

original = "I need to go home now"
message = original.replace("home ", "")  # remove the word "home "
print(message)  # shows "I need to go now"

If needed, you can also re-assign the same variable with the new string value:

original = original.replace("home ", "")