Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

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
229,783 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 ", "")