Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 222
iiooii Avatar asked Nov 28 '25 11:11

iiooii


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 * * >
like image 147
Patrick Artner Avatar answered Nov 30 '25 00:11

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!