vendredi 27 février 2015

Most Efficient Way to Replace Multiple Characters in a String

Let's say there is a string of any length, and it only contains the letters A through D:



s1 = 'ACDCADBCDBABDCBDAACDCADCDAB'


What is the most efficient/fastest way to replace every 'B' with an 'X' and every 'C' with a 'Y'.


Heres what I am doing now:



replacedString = ''
for i in s1:
if i == 'B':
replacedString += 'X'
elif i == 'C':
replacedString += 'Y'
else:
replacedString += i


This works but it is obviously not very elegant. The probelm is that I am dealing with strings that can be ones of milliions of characters long, so I need a better solution.


I can't think of a way to do this with the .replace() method. This suggests that maybe a regular expression is the way to go. Is that applicable here as well? If so what is a suitable regular expression? Is there an even faster way?


Thank you.


Aucun commentaire:

Enregistrer un commentaire