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!

4
  • Good find. I searched for a duplicate but with the "replace" term, not "find". Commented Nov 17, 2016 at 20:50
  • so did I: python replace words not partial words. I think the term "not partial word" was the key here. Commented Nov 17, 2016 at 20:52
  • at least now the "replace" part is covered :) Commented Nov 17, 2016 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! Commented Nov 17, 2016 at 21:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! This was perfect for my program!
@Jarred McMahan if an answer worked for you then please do accept it so that it is marked as 'Answered'.
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())

3 Comments

this wouldn't maintain the original whitespace since you are effectively replacing all whitespace with spaces. Also please give some info in your answer, just the single line of code isn't really all that helpful.
@Jean: couldnt agree more. thanks for the hints and tip (y)
not so bad if you don't want to use regex. and pythonic as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.