(easy question) Find and replace multiple items

Tim Chase python.list at tim.thechases.com
Tue Aug 8 17:04:43 EDT 2006


> Hello, i'm looking to find and replace multiple characters in a text
> file (test1). I have a bunch of random numbers and i want to replace
> each number with a letter (such as replace a 7 with an f  and 6 with a
> d). I would like a suggestion on an a way to do this.  Thanks

Well, the canonical way would be to use a tool designed to do 
transformations:

	tr '76' 'fd' < test1.txt > out.txt

However, if it's python you want:

 >>> mapping = {'7': 'f', '6': 'd'}
 >>> s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
 >>> ''.join([mapping.get(c, c) for c in s])
'ABCDEFGHIJKLMNOPQRSTUVWXYZ12345df890'

will transform all the items found in "s" according to the 
defined mapping.

Or, depending on your string length and the number of items 
you're replacing:

 >>> for k,v in mapping.items(): s = s.replace(k,v)

may be a better choice.  Or maybe they're both lousy choices. :) 
  Time it and choose accordingly.

-tkc







More information about the Python-list mailing list