Josh Dombal
Josh Dombal

Reputation: 155

How do I switch the first two letters of one string with the first two letters of the second string?

This is what I have so far.

def mix_up(a, b):

    a = a.replace(a[0:1], b[0:1])
    b = b.replace(b[0:1], a[0:1])

    return a + b

print mix_up('keegan', 'josh')

It returns: jeeganjosh

I need it to return joegan kesh

Upvotes: 1

Views: 1646

Answers (3)

Juergen
Juergen

Reputation: 12728

You are thinking to complicated. You don't need replace to replace exactly two characters, just do:

a, b = b[0:2]+a[2:], a[0:2]+b[2:]

I do it in one line here, because else I need at least one buffer variable for overwritten parts.

Upvotes: 4

Ryan
Ryan

Reputation: 2183

Without the use of a third variable

def mix_up(a, b):

    a, b = a.replace(a[0:2], b[0:2]) , b.replace(b[0:2], a[0:2])

    return a + " " + b

print mix_up('keegan', 'josh') #joegan kesh

Upvotes: 0

Cody Bouche
Cody Bouche

Reputation: 955

def mix_up(a, b):
    ao = a
    a = b[:2] + a[2:]
    b = ao[:2] + b[2:]

    return '{0} {1}'.format(a, b)

print mix_up('keegan', 'josh')
#joegan kesh

Upvotes: -2

Related Questions