rsplit and join could be used to simulate the effects of an rreplace
>>> 'XXX'.join('mississippi'.rsplit('iss', 1))
'missXXXippi'
Answer from Stephen Emslie on Stack Overflowpython replace characters in string from left to right - Stack Overflow
Right-to-left string replace in Python?
How to replace a character in a text file from left to right in python? - Stack Overflow
python - rreplace - How to replace the last occurrence of an expression in a string? - Stack Overflow
What is .replace in Python?
How do you replace part of a string in Python?
How do I replace a string in a list?
You could put the translations into a dict, and also combine the search-patterns into a single regular expression, which gives priority to the longer patterns. Then use the callback argument that re.sub accepts to make the replacement using the dict.
import re
trans = {
"00": "a",
"11": "b",
"01": "c",
"10": "d",
"0000": "e",
"1111": "f",
"0101": "g",
"1010": "h"
}
regex = "|".join(sorted(trans.keys(), key=len, reverse=True))
# demo
s = "0000000110110110100111111111"
result = re.sub(regex, lambda x: trans[x.group(0)], s)
print(result) # eacdbchcff
Non-regex approach would be to assess each section as a set of 4 characters, see if theres a match for those, or split into two halves of the 4 and get a match for them...
replacements = {'0000': 'e', '1111': 'f', '1010': 'h', '0101': 'g', '10': 'd', '01': 'c', '11': 'b', '00': 'a'}
s = "0000000110110110100111111111"
r_d = replacement_dict # only here to shorten comprehension
for i in range(0, len(s), 4):
print(r_d.get(s[i:i+4], r_d.get(s[i:i+2], "") +r_d.get(s[i+2:i+4],"")), end="")
or with loop as a list comprehension
"".join(r_d.get(s[i:i+4], r_d.get(s[i:i+2], "") +r_d.get(s[i+2:i+4], "")) for i in range(0, len(s), 4))
'eacdbcddcff'
Just build a new string only substituting the 2-char substrings at even indeces:
repl = {
'00': 'a',
'01': 'b',
'10': 'c',
'11': 'd',
}
filedata = ''.join(repl[filedata[i:i+2]] for i in range(0, len(filedata), 2))
Omitting the file handling, you could do this:-
mystring = '01110011'
mymap = {'00': 'a', '01': 'b', '10': 'c', '11': 'd'}
newstring = ''
while len(mystring) >= 2:
newstring += mymap[mystring[:2]]
mystring = mystring[2:]
print(newstring)
>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
Here is a one-liner:
result = new.join(s.rsplit(old, maxreplace))
Return a copy of string s with all occurrences of substring old replaced by new. The first maxreplace occurrences are replaced.
and a full example of this in use:
s = 'mississipi'
old = 'iss'
new = 'XXX'
maxreplace = 1
result = new.join(s.rsplit(old, maxreplace))
>>> result
'missXXXipi'