Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to make a list that is ['_', '_', '_'] with the length depending on a for loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!!

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading