'How to shift (right) a substring inside a string?
Suppose I have this string:
'0123456abcde78sdfnwjeabcde8923kasjsducuabcded999'
How can I move the substring 'abcde' two characters to the right to produce:
'012345678abcdesdfnwje89abcde23kasjsducud9abcde99'
So this:
s = '0123456abcde78'
t = 'abcde'
n = 2 # (right shift)
Function(s, t, n)
Should give:
'012345678abcde'
Edge cases that can be safely ignored:
- fewer characters than shift amount following substring (
'abcde1') - consecutive occurrences of the substring (
'abcdeabcde123')
Solution 1:[1]
I would use the regex-equivalent of replace - re.sub:
import re
s = "0123456abcde78sdfnwjeabcde8923kasjsducuabcded999"
t = 'abcde'
n = 2
print(re.sub(rf"({t})(.{{{n}}})", r"\2\1", s))
Gives:
012345678abcdesdfnwje89abcde23kasjsducud9abcde99
Explanation:
pattern:
(- First matching group:{t}- replacestusing f-strings - literally match the full substring.
)- End first group(- Second matching group:.- any character{{- escaped curly braces in f-string - to denote number of repetitions.{n}- f-string replacement ofn- the number of repetitions.}}- escaped closing braces.
)- End second group
replacement:
- Simply replace the order of the above groups.
Demo and explanations (without the f-strings) in regex101.com
To do a left shift instead, just change the order of the groups (i.e. first match any n characters and then match t):
re.sub(rf"(.{{{n}}})({t})", r"\2\1", s)
Solution 2:[2]
Python strings are immutable, so you will have to create a new string from:
- the beginning up to the index of
tins ncharacters starting from the end oft(so at `s.index(t) + len(t))t- the end of the string starting at
ncharacters past the end of t
In Python is could be:
def function(s, t, n):
ix = s.index(t)
length = len(t)
return s[:ix]+ s[ix + length: ix + length + n] + t + s[ix + length + n:]
Error and corner case handling are omitted per your requirement...
Solution 3:[3]
Make a new string according to the position of the index of the string you are looking for. Something among the following lines:
s = '0123456abcde78'
t = 'abcde'
n = 2 # (right shift)
tmp = s.index(t)
new_s = s[:tmp] + s[tmp+len(t):tmp+len(t)+n] + t + s[tmp+len(t)+n:]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Serge Ballesta |
| Solution 3 | Tomerikoo |
