(easy question) Find and replace multiple items

D

ds4ff1z

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
 
M

Mark Peters

ds4ff1z said:
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

how about:
'foo bar yd spam joepfd'

Mark Peters
 
T

Tim Chase

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:

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

-tkc
 
D

ds4ff1z

Tim said:
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:

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

-tkc


Thanks for the solutions!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top