Floofk
Floofk

Reputation: 113

Python list, .replace() problems

sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'                       
for i in sentence:
    if i.isalpha() == True:
        if i[0] in vowels:
            print(i + "way")
            new = i + "way"
            sentence.replace(i, new)
        else:
            print(i[1:] + i[0] + "ay")
            new = i[1:] + i[0] + "ay"
            sentence.replace(i, new)
    else:
        print(i)
print(sentence)

I am trying to make a piglatin sentence converter, I have been able to make the converter print the correct values for the translation, but I cannot make the program change the actual values of the list, which I need it to do so that I can print the converted text like the original, in a string format like "I like rabbits" instead of a list like:

I would like to know how I use the replace() function to change my list inside my for loop and if statements. If there is another way that is better that would be even better. Thank You.

Upvotes: 0

Views: 3734

Answers (2)

tijko
tijko

Reputation: 8312

Your list doesn't have a .replace method but, the str's in the list do.

It looks as though you are wanting to modify your list while iterating through the items.

sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'                       
for idx, word in enumerate(sentence):
    if word.isalpha() == True:
        if word[0] in vowels:
            print(word + "way")
            new = word + "way"
        else:
            print(word[1:] + word[0] + "ay")
            new = word[1:] + word[0] + "ay"
        sentence[idx] = new
    else:
        print(word)
print(sentence)

The enumerate builtin is especially useful when iterating and modifying items.

Upvotes: 0

Maciej Gol
Maciej Gol

Reputation: 15864

sentence.replace(i, new) function returns the new string - it doesn't do replacement in-place (on the original string).

You'd want to loop through indexes to easily modify the list being iterated over (you don't change your wheels whilst driving, do you?):

sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'                       
for idx in range(len(sentence)):
    to_replace = sentence[idx]
    if to_replace.isalpha() == True:
        if to_replace[0] in vowels:
            print(to_replace + "way")
            new = i + "way"
        else:
            print(to_replace[1:] + to_replace[0] + "ay")
            new = to_replace[1:] + to_replace[0] + "ay"
        sentence[idx] = new
    else:
        print(to_replace)
print(sentence)

You don't really need to call replace() (which is a string method, not list). You'd assign to sentence[idx] instead.

Upvotes: 2

Related Questions