Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "Find-Replace whole word only" exist in python?

Tags:

Does "Find-Replace whole word only" exist in python?

e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like,

"new string oldstring boldstring bold"

can somebody help me?

like image 505
user441380 Avatar asked Sep 07 '10 11:09

user441380


People also ask

Does replace in Python replace all?

Note: If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.

How do you replace part of text in Python?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do you match a whole word in Python?

To match whole exact words, use the word boundary metacharacter '\b' . This metacharacter matches at the beginning and end of each word—but it doesn't consume anything. In other words, it simply checks whether the word starts or ends at this position (by checking for whitespace or non-word characters).

How do you replace one word with a string in Python?

replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify. The . replace() method returns a copy of a string.


1 Answers

>>> import re
>>> s = "old string oldstring boldstring bold"
>>> re.sub(r'\bold\b', 'new', s)
'new string oldstring boldstring bold'

This is done by using word boundaries. Needless to say, this regex is not Python-specific and is implemented in most regex engines.

like image 74
Yuval Adam Avatar answered Oct 25 '22 17:10

Yuval Adam