Sunshine
Sunshine

Reputation: 49

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:

Upvotes: 1

Views: 339

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19414

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} - replaces t using 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 of n - 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)

Upvotes: 2

Bart Barnard
Bart Barnard

Reputation: 1168

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:]

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 148900

Python strings are immutable, so you will have to create a new string from:

  • the beginning up to the index of t in s
  • n characters starting from the end of t (so at `s.index(t) + len(t))
  • t
  • the end of the string starting at n characters 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...

Upvotes: 1

Related Questions