0

I am helping a friend with Python and I might be getting confused with C++. So I am curious as to why this would not work. The expected function of this is a Pig Latin translator so if there is a vowel as the first letter 'ay' is added to the end but if the first letter is a consonant, that letter is added to the end and then the 'ay' is added. Example: apple --> appleay watch --> atchway Sorry I completely forgot to post the code (edit)

vowel = ['a','e','i','o','u']
counter = -1
while True: 
    text = input("Write a word to translate. If you do not want to play anymore, 
write exit: ")
if text == "exit":
    break  

elif text[0].lower() in vowel:
    text = text + 'ay'
    print(text)

elif text[0].lower() not in vowel:
    letter = text[0]
    length = len(text) - 1
    for i in range(1, length):
        text[i-1] = text[i]
    text[length + 1] = letter
    print(text)
4
  • 1
    Where is the function? Commented Jul 12, 2018 at 1:37
  • Could you post the code you have so far? Commented Jul 12, 2018 at 1:39
  • So the consonant is removed from the first letter as well? Commented Jul 12, 2018 at 1:41
  • Sorry, forgot to add the code. Commented Jul 12, 2018 at 1:42

1 Answer 1

1

Strings are immutable, so you can't assign to a string at specific index like text[i-1] = text[i].

Instead, use text = text[1:] + text[0] + 'ay' to do what you want:

vowel = ['a','e','i','o','u']
counter = -1
while True:
    text = input("Write a word to translate. If you do not want to play anymore, write exit: ")
    if text == "exit":
        break

    elif text[0].lower() in vowel:
        text = text + 'ay'
        print(text)

    elif text[0].lower() not in vowel:
        text = text[1:] + text[0] + 'ay'
        print(text)
Sign up to request clarification or add additional context in comments.

3 Comments

You can just use else for text[0].lower() not in vowel , I think.
I know that that is an option but is there a way for me to individually access the indices of the string and reassign the value like how I tried to do in my original code?
@RyanMarvin If you want to do it in your original way, you can cast the string to a list first (like letters = str(text)) so that you can assign values to it at specific indexes, and then convert the list back with join (like ''.join(letters)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.