0

Want to replace a certain words in a string but keep getting the followinf result:

String: "This is my sentence."

User types in what they want to replace: "is"

User types what they want to replace word with: "was"

New string: "Thwas was my sentence."

How can I make sure it only replaces the word "is" instead of any string of the characters it finds?

Code function:

import string
def replace(word, new_word):
   new_file = string.replace(word, new_word[1])
   return new_file

Any help is much appreciated, thank you!

dsh
  • 12,037
  • 3
  • 33
  • 51
Jarred
  • 13
  • 4
  • Good find. I searched for a duplicate but with the "replace" term, not "find". – Jean-François Fabre Nov 17 '16 at 20:50
  • so did I: [python replace words not partial words](https://www.google.ca/search?client=safari&rls=en&q=python+replace+words+not+partial+words&oq=python+replace+words+not+partial+words&gs_l=serp.3...44021.51387.0.51523.33.30.0.3.3.0.127.2123.23j5.28.0....0...1c.1.64.serp..2.18.1097...0j0i67k1j0i131k1j0i22i30k1j33i21k1.0mLcUwAiDdk). I think the term "not partial word" was the key here. – Tadhg McDonald-Jensen Nov 17 '16 at 20:52
  • at least now the "replace" part is covered :) – Jean-François Fabre Nov 17 '16 at 20:54
  • @TadhgMcDonald-Jensen the trick is to google the keywords, just that I'm forgetting everytime. SO engine is good because you can filter tags using sqbrackets, but google is better for general search, and 99% of the time a SO answers pops up first! – Jean-François Fabre Nov 17 '16 at 21:13

2 Answers2

4

using regular expression word boundary:

import re

print(re.sub(r"\bis\b","was","This is my sentence"))

Better than a mere split because works with punctuation as well:

print(re.sub(r"\bis\b","was","This is, of course, my sentence"))

gives:

This was, of course, my sentence

Note: don't skip the r prefix, or your regex would be corrupt: \b would be interpreted as backspace.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

A simple but not so all-round solution (as given by Jean-Francios Fabre) without using regular expressions.

 ' '.join(x if x != word else new_word for x in string.split())
Falloutcoder
  • 991
  • 6
  • 19