0

I've created a small test for a bigger function I am trying to create. Right now I have a function that should take a string as input, locate and replace the letter 'a' with the upside-down version within the string, and return a new string containing the edited version of the old string. For some reason, however, when I attempt to run this function, the loop takes effect on the first letter of the string, but then breaks and fails.

I've run the code in the function in the IDLE3 REPL and it works fine. I'm trying to figure out why it doesn't translate into a function.

def upside_down(word): 
    new_word = [] # Empty list for creating the edited string.

    for letter in list(word):  # Splitting the string into a list and looping through.      
        if letter == 'a':
            new_word.append('\N{LATIN SMALL LETTER TURNED A}')
        else:
            new_word.append(letter)

        return ''.join(new_word) #Should return the new edited string.

As I said, I should be able to access the function like this:

upside_down('cab')

and receive this as an output:

'cɐb'
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • *"...but then breaks and fails."* Can you expand on this? Are you getting an exception? If so, include the full traceback. Are you getting incorrect results? Then describe what you're getting. – glibdud Feb 11 '19 at 21:02
  • 3
    Do not return inside the loop – DeepSpace Feb 11 '19 at 21:03
  • Well that was simple enough. Should go to show how new I am to coding. Thanks for the help. – J. Howard Feb 11 '19 at 21:06
  • 1
    Just a side note, but you don't need to convert your string to a list. Using `for letter in word:` will go through each letter in your word. – Jack Moody Feb 11 '19 at 21:18

1 Answers1

0

Is there a reason why you can not use the built-in replace function?

output = "cab".replace("a","ɐ")
print(output)

or in a function:

def upside_down(word):
    return word.replace("a","ɐ")
jeremyforan
  • 1,417
  • 18
  • 25