Bryan
Bryan

Reputation: 33

How can I move a word within a string?

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".

Upvotes: 3

Views: 4563

Answers (3)

NPE
NPE

Reputation: 500457

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.)

Upvotes: 5

jterrace
jterrace

Reputation: 67073

Here's what I would do. It splits the string into a list, moves the item, then joins it back together:

def move_word(s, word, pos):
   split = s.split()
   split.insert(pos, split.pop(split.index(word)))
   return ' '.join(split)

Here's an example:

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> move_word(s, 'quick', 2)
'The brown quick fox jumps over the lazy dog'
>>> move_word(s, 'jumps', 0)
'jumps The quick brown fox over the lazy dog'

Upvotes: 2

nvlass
nvlass

Reputation: 685

Well, this

r = lambda x, y, z: " ".join(x.split(" ")[0:x.split(" ").index(y)] + x.split(" ")[x.split(" ").index(y)+1:x.split(" ").index(y)+z] + [x.split(" ")[x.split(" ").index(y)]] + x.split(" ")[x.split(" ").index(y)+z:])

is probably NOT pythonic, but it is fun.

(not to mention highly not optimal)

Upvotes: 2

Related Questions