Home > Enterprise >  Is there a way to replace a random word in a list?
Is there a way to replace a random word in a list?

Time:11-17

Here is what I am trying to do:

  1. Pick a random word from a list

  2. Ask the user of a word to replace it with

  3. Print out the list with the word replaced

So I have the random word picker part finished, but I don't know how to replace the word with the input. I thought I could use the .replace() function, but it's a list. Here is the code:

import random

all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
    print(x)

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    random = random.choice(all_lists) #this picks the random word
    replace_word = input("What would would you like to replace the word with?")
    all_lists_replace = all_lists.replace(random, replace_word)
    print(all_lists_replace)

if appending_list == ("No"):
    exit()

CodePudding user response:

Use index

from random import randrange

all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
    print(x)

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    idx = randrange(len(all_lists))
    replace_word = input("What would would you like to replace the word with?")
    all_lists[idx] = replace_word
    print(all_lists)

CodePudding user response:

Instead of selecting a random choice from the list, I suggest you select a random index. That way, you can replace that element of the list by simply assigning the user's input to that index of the list.

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    ix = random.randint(0, len(all_lists))
    replace_word = all_lists[ix]
    replacement = input(f"What should I replace {replace_word} with?")
    all_lists[ix] = replacement
  • Related