0

I need my program to replace a certain - with a variable. I've tried this but it replaces the whole thing with the varibale.

jelenleg = 8 * "-"
x = 0
guess = c
jelenleg = jelenleg[x].replace("-", guess)
print(jelenleg)

So I need this to happen:
before: --------
after: c-------
But instead what I get is this: c

4
  • @charelf omg how didnt i think of that thanks so much :) Commented Dec 12, 2021 at 20:15
  • Happy I could help! Also as a suggestion for the future, try maybe using a bit more descriptive titles, makes it easier to find answers! And if someone gives you the answer, you can accept it by clicking on the checkmark. Commented Dec 12, 2021 at 20:23
  • @charelf :) Sorry Im a student I started programming a month ago so Im still learning a lot (including stackoverflow) :) Thanks again Commented Dec 12, 2021 at 20:26
  • No problem, we all started somewhere, have fun programming and using Stack overflow:) Commented Dec 13, 2021 at 8:36

1 Answer 1

2

You can specify the count of to be replaced items:

jelenleg.replace("-", guess, 1)

will only replace one -

To replace at a particular location, I can't think of anything easier than transforming the string into a list, then replacing, then back to a string, like this:

jelenleg_list = list(jelenleg)       # str --> list
jelenleg_list[x] = guess             # replace at pos x
jelenleg = "".join(jelenleg_list)    # list --> str
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.