How do I send a character from a string that is NOT a letter or a number to the end of the string?

Tags:



I am doing a Pig Latin code in which the following words are supposed to return the following responses:

"computer" == "omputercay"
"think" == "inkthay"
"algorithm" == "algorithmway"
"office" == "officeway"
"Computer" == "Omputercay"
"Science!" == "Iencescay!"

However, for the last word, my code does not push the ‘!’ to the end of the string. What is the code that will make this happen?

All of them return the correct word apart from the last which returns “Ience!Scay!”

def pigLatin(word):
    vowel = ("a","e","i","o","u")

    first_letter = word[0]
    if first_letter in vowel:
        return word +'way'

    else:
        l = len(word)
        i = 0
        while i < l:
            i = i + 1
            if word[i] in vowel:
                x = i
                new_word = word[i:] + word[:i] + "ay"

                if word[0].isupper():
                    new_word = new_word.title()

                return new_word

Answer

For simplicity, how about you check if the word contains an exlamation point ! at the end and if it does just remove it and when you are done add it back. So instead of returning just check place ! at the end (if you discovered it does at the beggining).

def pigLatin(word):
    vowel = ("a","e","i","o","u")

    first_letter = word[0]
    if first_letter in vowel:
        return word +'way'

    else:
        hasExlamation = False

        if word[-1] == '!':
            word = word[:-1] # removes last letter
            hasExlamation = True

        l = len(word)
        i = 0
        while i < l:
            i = i + 1
            if word[i] in vowel:
                x = i
                new_word = word[i:] + word[:i] + "ay"

                if word[0].isupper():
                    new_word = new_word.title()

                break # do not return just break out of the `while` loop
        if hasExlamation:
            new_word += "!" # same as new_word = new_word + "!"
        return new_word
        

That way it does not treat ! as a normal letter and the output is Iencescay!. You can of course do this with any other character similarly

specialCharacters = ["!"] # define this outside the function

def pigLatin():
    # all of the code above
    if word in specialCharacters:
        hasSpecialCharacter = True
    # then you can continue the same way


Source: stackoverflow