Print elements of a list in input() prompt without .join and converting list to str

Viewed 68

I have a list that will vary in length e.g guessed = ["w", "o", "*", "*"]

It needs to be displayed as: Guess a letter: w o * * < and then take in user input.

Limitations Set By Teacher:

  • I can't use list methods such as .join()
  • I can't convert guessed to a str

My Code

def printList(guessed):
  return print(*guessed, end=" ")
  
userGuess = input("Guess a letter %s > \n " % printList(guessed))

Output

w o * * Guess a letter None > 

I know this is happening because I'm concatenating a None type to the string in input() prompt but I'm not sure how to fix this.

Another Potential Idea:

Create a function that takes the length of guessed and slices it, for example, guessed[0] + guessed[1] + .... but I'm not sure how I would do this given that I need to have this inside the input() prompt and it needs to generalize to the length of guessed (which will be changing).

I've been trying out new things for hours and this is the best I've come up with so far, any recommendations and advice would be really appreciated.

1 Answers

Create a format string based on the length of the list:

# use '{} ' for each elem of list and multiply it by its len to get correct amounts
# then you can use that inside input and format the decomposed list into it:
formatstring = "Guess a letter " + '{} '*len(guessed) + "> \n " 
input( formatstring.format(*guessed) )

Output:

Guess a letter w o * * >
Related