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

How do you replace individual charachters in a string?

Im wondering how i would go about replacing an individual letter in a string. Say i have the follwing code:

While True:
    print("------")

If i later want to be able to replace those "-" individually with something else, how would i go about doing that?

1 Answer

Steven Parker
Steven Parker
243,656 Points

In Python, strings are immutable, which means they cannot be changed. But you can re-assign a variable that represents a string with a new string anytime you want. The new string can be created from the old one with certain charater(s) changed. Here's an example that stores a string in the variable "s" and rebuilds it using slices:

s = "------"
print(s)  # ------
s = s[:2] + 'a' + s[3:]                                                                                 
print(s)  # --a---

Thank you very much sir!