'How to mix strings in Python

I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid

My code only returns pox mix

Code:

def mix_up(a, b):
    if len(a and b)>1:
        b=str.replace(b,b[2],a[2:3])
        a=str.replace(a,a[2],b[2])
        print b,"",a
    return
mix_up('mix','pod')

I am seeking to do this for multiple words. So another example:

if I used dog,dinner

The output should return dig donner

Thanks!



Solution 1:[1]

Little play on string slicing

def mix_up(first, second):
    new_first = second[:2] + first[2:]
    new_second = first[:2] + second[2:]
    return " ".join((new_first, new_second))

assert mix_up('mix','pod') == 'pox mid'
assert mix_up('dog','dinner') == 'dig donner'

Solution 2:[2]

If you simply wanted to put the 2nd word before the first word all the time:

def mix_up(a,b):
    return " ".join([b,a])   # Should return pod mix

Give that you aimed for pox mix suggests that you probably wanted to:

1) Replace the last character of word b with x 2) Place b before a.

In that case, the function would be:

 def mix_up(a,b):
    b = b.replace(b[len(b)-1], 'x') # 'x' could be any other character
    return " ".join([b,a])   # Should return pox mix

you can simply swap b with a in order to change the position of the words.

If you didn't want the space in metween:

return "".join([b,a])

UPDATE

to "swap" the second letter between b and a, I simply correct your function like the following:

def mix_up(a, b):
    if len(a and b)>1:
        temp = b[1] # Store it in a temp
        b=str.replace(b,b[2],a[2:3])
        a=str.replace(a,a[2],b[2])
        print (b,"",a)
    return
mix_up('mix','pod')

Your only problem was once you replaced b, you were using the new b to chose the 2nd letter and replace into a.

Solution 3:[3]

def mix_up(a, b):
  if len(a) < 2 or len(b) < 2: return
  return (b[:2] + a[2:] + " " + a[:2] + b[2:])

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 Łukasz Rogalski
Solution 2
Solution 3 Pooja Kose