Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_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

like image 901
Teifion Avatar asked Apr 18 '09 22:04

Teifion


People also ask

How do you use replace for a list of strings in Python?

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 .

Can we use Replace in list in Python?

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.

Can you replace multiple strings in Python?

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.

How do you replace multiple elements in a list in Python?

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.


2 Answers

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) 
like image 129
Rick Copeland Avatar answered Sep 20 '22 23:09

Rick Copeland


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) 
like image 20
Matthew Schinckel Avatar answered Sep 22 '22 23:09

Matthew Schinckel