[SOLVED] How to mix strings in Python

Issue

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

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'

Answered By – Ɓukasz Rogalski

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *