How can I move a word within a string?

python, python-2.7

Solution

Not sure if I'd call this "slick", but it does the job and is pretty straightforward:

def reorder(s, word, delta):
  words = s.split()
  oldpos = words.index(word)
  words.insert(oldpos+delta, words.pop(oldpos))
  return ' '.join(words)

print reorder('The quick brown fox jumps over the lazy dog', 'quick', 2)

(I assume that the 2 in your example is the number of positions by which to move the word.)

Problem

Is there a "native" way in Python 2.7 to move a word (space-delimited substring) within a longer string? Basically, what I'm looking for is: ``` ret = 'The quick brown fox jumps over the lazy dog'.move_word('quick',2) # ret = 'The brown fox quick jumps over the lazy dog' ``` My thought is to go about it by writing a function to split into a list, iterate through the list for matches, and then reorder as I find the word. My question is really about finding out if there are "slick"/Pythonic ways to do this instead. Thanks! EDIT: Per comments below: the numeric parameter in the example above was intended to specify a "delta" in number of words. For the above example, 2 was meant to mean "move 'quick' 2 words to the right".

Original source