After finding the fastest string replace algorithm in this thread, I've been trying to modify one of them to suit my needs, particularly this one by gnibbler.
I will explain the problem again here, and what issue I am having.
Say I have a string that looks like this:
str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"
You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dictionary, like so:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m"}
Using gnibblers solution provided in my previous thread, I have this as my current solution:
myparts = tmp.split('&')
myparts[1:]=[dict.get(x[0],"&"+x[0])+x[1:] for x in myparts[1:]]
result = "".join(myparts)
This works for replacing the characters properly, and does not fail on characters that are not found. The only problem with this is that there is no simple way to actually keep an ampersand in the output. The easiest way I could think of would be to change my dictionary to contain:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m",
"&":"&"}
And change my "split" call to do a regex split on ampersands that are NOT followed by other ampersands.
>>> import re
>>> tmp = "&yI &creally &blove A && W &uRootbeer."
>>> tmp.split('&')
['', 'yI ', 'creally ', 'blove A ', '', ' W ', 'uRootbeer.']
>>> re.split('MyRegex', tmp)
['', 'yI ', 'creally ', 'blove A ', '&W ', 'uRootbeer.']
Basically, I need a Regex that will split on the first ampersand of a pair, and every single ampersand, to allow me to escape it via my dictionary.
If anyone has any better solutions please feel free to let me know.