Home > other >  How to replace an element in a list with an existing variable?
How to replace an element in a list with an existing variable?

Time:02-14

I can't replace an element in a list with a variable and I'm not sure how. I've checked everywhere and I can't find it. Can someone let me know how to? Cheers

import random
passcode = "x"
while passcode == "x":
  randomword = list(input("Please enter a random word: "))
  randomwordtwo = list(input("Please enter a second random word: "))
  randomwordthree = list(input("Please enter a final random word: "))
  randomword.extend(randomwordtwo)
  randomword.extend(randomwordthree)
  symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
  number = ["0","1","2","3","4","5","6","7","8","9"]
  print(randomword)
  randsymb = (random.choice(symbol))
  for i in range(len(randomword)):
    if randomword[i] == "a":
      randomword[i] = (randsymb)

CodePudding user response:

There doesn't have replace() method for a list

But you can use str.replace() on a string.

there is an example on w3schools

CodePudding user response:

From what you have written, your final line replaces the letter "a" with a randomly selected symbol and so appears to answer your own question. Therefore, I will try and help with what I think you mean.

If you want to try and replace a random letter within your list instead of strictly the letter "a", try:

import random
import string
passcode = "x"
while passcode == "x":
    randomword = list(input("Please enter a random word: ").lower().strip())
    randomwordtwo = list(input("Please enter a second random word: ").lower().strip())
    randomwordthree = list(input("Please enter a final random word: ").lower().strip())
    randomword.extend(randomwordtwo)
    randomword.extend(randomwordthree)
    symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
    number = ["0","1","2","3","4","5","6","7","8","9"]
    print(randomword)
    randsymb = (random.choice(symbol))
    random_letter = ""
    while random_letter not in randomword:
        # finds random letter from randomword to replace
        random_letter = random.choice(string.ascii_letters)
    for i in range(len(randomword)):
        # replaces random letter with symbol
        if randomword[i] == f"{random_letter}":
            randomword[i] = randsymb
    # produces final random word
    final_word = "".join(randomword)
    print(final_word)
  • Related