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
Python Script editor.replace Bug? concerning the characters '(' and ')' | Notepad++ Community
python - Left shift but replace the shifted bits with ones - Stack Overflow
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
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'
There's no such function built in, or, for that matter, available in any extension library I know of.
It's pretty easy to do yourself, though. Say the int is n and you want to shift it left by s bits.
First flip all the bits of n (change all 0 bits to 1, and all 1 bits to 0). Then shift left by s. That adds s 0 bits on the right. Then flip the bits again. The new trailing 0 bits are changed to 1 bits, and the original bits of n are restored.
>>> n = 5
>>> bin(n)
'0b101'
>>> ~(~n << 6)
383
>>> bin(_)
'0b101111111'
Is x = (x << y) | ((1 << y) - 1) what you're looking for?
First, we shift x left y bits:
x = 21
y = 2
bin(x) == 10101 (in binary)
x << y == 1010100
Then, the number ((1 << y) - 1) gives us a number with only the y lowest bits set to 1, e.g.
1 << 2 == 100
(1 << 2) - 1 == 011
Finally, we or them to get 1010100 | 11 == 1010111.
word1 = input("Word: ") # lets say that the given word is "tower"
word2 = "********************"
word2 = word2.replace(word[3], word[3])
print(word2)
# Now the my code replaces all the "*" characters with the character "e"
# It just prints "eeeeeeeeeeeeeeeeeeee"
# I would like the code only to replace the 4th character with the other strings 4th
# I'd like it to print "***e****************"