Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: String Replace only if whole word?

Thread Tools

Re: String Replace only if whole word?

Tim Chase
Posts: n/a
> I have been using the string.replace(from_string, to_string, len(string))
> to replace names in a file with their IP address.
> For example, I have definitions file, that looks something like:
> WIN2000
> and I have a text file (a Python script) that has these names in the file.
> In most cases the string.replace() command works great. But there is one
> instance which it fails:
> Suppose I had in the file:
> if (LAPTOP_IS_UP()):
> It would replace the string with:
> if (""_IS_UP()):
> Is there any easy way to avoid this, only replace if a whole
> word matches? I probably need something which determines when
> a word ends, and I will define a word as containing only
> 'A'-'Z','a'-'z','0'-'9','_' . As long as the string contains
> more of the word digits after the match, don't replace?

A solution I've used in the past (whether it's good or not, I'd
be interested to get feedback from the list)

>>> mapping = {}
>>> for line in file('definitions.txt'):

.... ip, name = line.split()
.... mapping[name] = '"%s"' % ip
>>> import re
>>> r = re.compile(r'\b\w+\b')
>>> r.sub(lambda match: mapping.get(,, s)

The regexp '\b\w+\b' finds "word"s (where \w is locale specific,
but could easily be rewritten as '\b[a-zA-Z0-9_]+\b' if you
needed) while the '\b' portion ensures that there's a
word-to-non-word boundary coming or going.

It then goes through and replaces every word in the string with
either the result of looking it up in the magic mapping, or with
its original contents.


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Win32::TieRegistry -- replace string in the whole HKLM MoshiachNow Perl Misc 0 11-21-2006 09:57 AM
RE: String Replace only if whole word? Michael Yanowitz Python 1 11-19-2006 10:38 PM
RE: String Replace only if whole word? Carsten Haese Python 0 11-17-2006 04:03 PM
String Replace only if whole word? Michael Yanowitz Python 1 11-17-2006 01:38 PM
*WITHOUT* using: ValidateRequest="False" for the whole page (or my whole site).... \A_Michigan_User\ ASP .Net 2 08-21-2006 02:13 PM