Skip to content Skip to sidebar Skip to footer

A List Of String Replacements In Python

Is there a far shorter way to write the following code? my_string = my_string.replace('A', '1') my_string = my_string.replace('B', '2') my_string = my_string.replace('C', '3') my_s

Solution 1:

Looks like a good opportunity to use a loop:

mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
fork, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

A faster approach if you don't mind the parentheses would be:

mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
fork, v in mapping:
    my_string = my_string.replace(k, v)

Solution 2:

You can easily use string.maketrans() to create the mapping string to pass to str.translate():

importstring
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)

Solution 3:

If you want to get the wrong answer, slowly, then use string.replace in a loop. (Though it does work in this case of no overlap among the patterns and replacements.)

For the general case with possible overlaps or a long subject string, use re.sub:

import re

defmultisub(subs, subject):
    "Simultaneously perform all substitutions on the subject string."
    pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
    substs = [s for p, s in subs]
    replace = lambda m: substs[m.lastindex - 1]
    return re.sub(pattern, replace, subject)

>>> multisub([('hi', 'bye'), ('bye', 'hi')], 'hi and bye')
'bye and hi'

For the special case of 1-character patterns and 1- or 0-character replacements, use string.maketrans.

Solution 4:

Also look into str.translate(). It replaces characters according to a mapping you provide for Unicode strings, or otherwise must be told what to replace each character from chr(0) to chr(255) with.

Solution 5:

replaceDict = {'A':'1','B':'2','C':'3','D':'4','E':'5'}       
for key, replacement in replaceDict.items():  
  my_string = my_string.replace( key, replacement )

Post a Comment for "A List Of String Replacements In Python"