0

A question I came up with:

I'm trying to write a function that replaces the first and the fourth letter of a word with the same letter just capitalized. Currently I am working with the string.replace() method. It works great for most of the time, except when there is an equal letter to the one on the fourth place before it. Example: "bananas" What I would expect the program to do is to return "BanAnas" but for a reason it return "BAnanas". If I use the word "submarine" it would just work fine, "SubMarine".

The code I wrote is this:

def old_macdonald(name):
    name = name.replace(name[0], name[0].upper(), 1)
    name = name.replace(name[3], name[3].upper(), 1)
    return name

Can someone explain why this is happening?

Matthias
  • 12,873
  • 6
  • 42
  • 48
  • Adjust your code. Add 4 spaces in beginning of each code line. – Mace Apr 13 '20 at 11:03
  • Run over each character and make it uppercase if the index matches: `[c.upper() if i in (0, 3) else c for i, c in enumerate('Bananas')]`. Simple thing left to do is [joning](https://docs.python.org/3/library/stdtypes.html#str.join) that back to a string (I'll leave that for exercise). – Matthias Apr 13 '20 at 11:09

1 Answers1

0

It's because name.replace(name[3], name[3].upper(), 1) looks for the first character matching name[3]. Stop using replace altogether, chop up your string by slicing.

GKFX
  • 1,386
  • 1
  • 11
  • 30