Austin Whitelaw
Austin Whitelaw

Reputation: 107

Switching first letter of two strings in Python?

I'm doing some of the Google python exercises, this one on strings.

I've come across one where it asks to switch the first two letters of each of two strings.

So it has a function created called mix_up, and you basically have to create the definition. So basically I made two variables that hold each of the first two letters, and then I use the replace function, then add them together, and it should work. But instead I get the original strings added together, the letters are not switched.

def mix_up(a, b):
    first = a[0:2]
    second = b[0:2]
    a.replace(first, second)
    b.replace(second, first)
    phrase = a + " " + b
    return phrase

Upvotes: 1

Views: 2417

Answers (3)

Crowman
Crowman

Reputation: 25926

Note that replace() will replace all of the occurrences, not just the first, unless you specify otherwise. You can do this easily enough with something like:

def mix_up(a, b):
    new_a = b[0:2] + a[2:]
    new_b = a[0:2] + b[2:]
    phrase = new_a + " " + new_b
    return phrase

or more concisely:

def mix_up(a, b):
    return b[0:2] + a[2:] + " " + a[0:2] + b[2:]

You can also do replace(first, second, 1), where that last argument is the maximum number of occurrences to replace.

Upvotes: 3

Nino Walker
Nino Walker

Reputation: 2903

replace is not destructive, it creates a new object.

So reassign your values, e.g.: a = a.replace(first, second)

Upvotes: 2

Brionius
Brionius

Reputation: 14108

The problem is that the replace method returns a new string, rather than changing the original.

Try this instead:

a = a.replace(first, second)
b = b.replace(second, first)

Upvotes: 3

Related Questions