Selectively replace multiple instances of a character within a string: Difference between revisions
Selectively replace multiple instances of a character within a string (view source)
Revision as of 09:45, 13 June 2022
, 2 years ago→{{header|Python}}
m (→{{header|Lambdatalk}}: small edit) |
|||
Line 307:
"AErBcadCbFD"
</pre>
=={{header|Python}}==
{{trans|Julia}}
<lang python>from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)
seen[c] += 1
return ''.join(newchars)
print('abracadabra ->', trstring('abracadabra', rep))
</lang>
=={{header|Raku}}==
|