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_string = my_string.replace('D', '4') my_string = my_string.replace('E', '5')
Note that I don't need those exact values replaced; I'm simply looking for a way to turn 5+ lines into fewer than 5
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.
Replace multiple different characters: translate()Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
Looks like a good opportunity to use a loop:
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'} for k, 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') ] for k, v in mapping: my_string = my_string.replace(k, v)
You can easily use string.maketrans() to create the mapping string to pass to str.translate():
import string trans = string.maketrans("ABCDE","12345") my_string = my_string.translate(trans)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With