1

I want to replace the word 'I' in a sentence by the word 'you', and many other such examples. This is not that difficult, except that the 'I' in a word like 'Instagram' is now also being replaced - which I do not want. I would expect this is very simple but cannot find the solution (I am still inexperienced in programming). Here is my code.

s = 'I can increase my number of Instagram followers'
i = s.split()
i = [i.replace('I', 'you') for i in i]
i = [i.replace('my', 'your') for i in I]
i = " ".join(i)

This gives:

You can increase your number of younstagram followers.

But how do you get this result?

You can increase your number of Instagram followers.

EDIT

I have changed the title of the question
FROM: How to find a word in a string that is not part of another word? Python.
TO: How to replace a word in a sentence ONLY IF that word appears on its own and is not part of another word? Python

This question was marked as a duplicate of Check if string appears as its own word - Python.

However, the answers there only seem to check if a given word appears in a sentence as its own word (not as part of another word) and return a boolean. However, knowing that may be a necessary condition but is not a sufficient condition for replacing that word by something else – which is my goal. Therefore, my question may not be a duplicate of the question it is now linked with.

The following would be simple solutions, but do not work:

i = [i.replace(' I ' , 'you') for i in i] # white space left and right of 'I'
i = [i.replace('''I''', 'you') for i in i]

Any suggestions how to solve this problem?

twhale
  • 725
  • 2
  • 9
  • 25
  • Will "I" always be the at the beginning of a sentence, or could it be elsewhere, e.g. "I, and you, want the same result"? Any whitespace-splitting method may be difficult to implement and your problem may be non-trivial. – jpp May 15 '18 at 09:40
  • 1
    You cannot do that with only `replace` function or at least in a very clean way. Instead you can sue regular expressions. In this case you can use `re.sub` with a proper replacer function. – Mazdak May 15 '18 at 09:42
  • 1
    @Ignacio Vazquez-Abrams I don't think if that's a proper duplicate target. However I added another but more related dup. – Mazdak May 15 '18 at 09:44
  • @jpp The 'I' is not always at the beginning of a sentence, it can be anywhere in the string. – twhale May 15 '18 at 09:45
  • @ Kasramvd: do you know how to do this with regular expressions? I tried to identify ' I ', but did not succeed. That is, 'I' with a space before and after it. – twhale May 15 '18 at 09:47
  • @twhale: Did you try `re.sub()`? – Ignacio Vazquez-Abrams May 15 '18 at 14:16
  • @Ignacio Vazquez-Abrams: Yes, I tried that. The following seems to work: `i = re.sub(r'\bmy\b', 'your', i)`. Thanks a lot! – twhale May 15 '18 at 16:26

0 Answers0