I'm trying to make a list of 'blanks' that can be filled in individually later. The length of the list is dependent on a value (currentWord
) which is why I can't hard-code it.
iter8 = len(currentWord)
for i in currentWord:
answerListNEW.append(' ')
#
for i in currentWord:
answerListNEW[i] = '_'
I get errors that the index must be integer, not str. Is there a way for the program to accept the 'blank space' ? For simplicity, lets say currentWord = 'alpha' so that it's simple and there's just 5 iterations.
SECONDLY, I would also like to print that list as a concatenated string so it's just '_____'. (That way when values are added it becomes 'v' and such.
Thanks in advance!!
CodePudding user response:
i in currentWord
will iterate over letters of that string (assuming it is a string). As the error says, lists cannot be indexed by letters.
You can use range()
answerListNEW = ['_' for _ in range(len(currentWord))]
Or list multiplication
answerListNEW = ['_'] * len(currentWord)
Or "listing" a string of all underscores
answerListNEW = list('_' * len(currentWord))
also like to print that list as a concatenated string
print(''.join(answerListNEW))
CodePudding user response:
I would also like to print that list as a concatenated string so it's just '_____'
A string has most of the same properties as a list already, so why bother making the list, only to convert it to a string.
You can just do something like
answerListNew = '_' * len(currentWord)
if you want a string the same length as currentWord
containing all '_' characters.
For an actual list of letters (allowing you to modify the letters one by one), you can do
answerListNew = ['_'] * len(currentWord)
and convert it to string form with
answerStrNew = ''.join(answerListNew)