'Using a List of Lists as parameters for changing letters in a string
I want to be able to take a string string = Cookie and replace specific letters with the parameters of a list of lists list = [[C,3], [i,1]].
I know you can use string.replace(C,3) for example to replace just the C but I want it to go through the specified list and change any corresponding letters. I've tried changing the list to a string and using a for loop to iterate over list in string , but it does not work. Any suggestions?
this is what I have so far:
myString = "Mississippi"
pairsList = [['i', '1'], ['s', '$'], ['p', 'z']]
pairslist = ''.join(pairsList)
for i in myString:
if pairslist in myString:
newString = myString.replace[pairslist]
Solution 1:[1]
You could use the translate method. For example,
mapping = str.maketrans({'C':'3','i':'1'})
print('Cookie'.translate(mapping))
The resulting output is 3ook1e.
To match the example from the question:
myString = "Mississippi"
pairsList = [['i', '1'], ['s', '$'], ['p', 'z']]
mapping = str.maketrans(dict(pairsList))
print(myString.translate(mapping))
The result is M1$$1$$1zz1.
Solution 2:[2]
IF you really wanted to do this with loops, you'd loop over the replacements:
myString = "Mississippi"
pairsList = [['i', '1'], ['s', '$'], ['p', 'z']]
for old,new in pairsList:
myString = myString.replace(old,new)
But the translate solution is really the correct one here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tim Roberts |
