0

I have a problem. I am trying to remove a specific word from a string like this:

sentence = "My father always told me to find a girl, so I can be a father in the future"
sentence = sentence.replace("father", '')

But I only want to remove the word father in the first part of the sentence. I can't find something like that on a python explanation of the replace function.

Is this possible and what do I need to use then?

1
  • Yes..... Just 1 variable more? Commented Nov 5, 2020 at 18:31

2 Answers 2

2

Just gotta add a number in replace to tell it how many times to replace.

sentence = sentence.replace("father", '', 1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I will accept when I can!
0

The docs states:

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

So pass a 3rd argument, like so:

sentence = "My father always told me to find a girl, so I can be a father in the future"
sentence = sentence.replace("father", '', 1)
print(sentence)
My  always told me to find a girl, so I can be a father in the future

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.