Reputation: 3
I've tried looking at other solutions for this issue, but none of them work or make sense to me.
relevant code:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
options = ["option 1", "option 2", "option 3", "option 4"]
choices = alphabet[0:len(options)]
for i in options:
print(choices[i], options[i])
Output: print(choices[i], options[i]) TypeError: string indices must be integers
I'm looking to get the following output:
a option 1
b option 2
c option 3
d option 4
Anyone know what I'm screwing up here? Thanks in advance
Upvotes: 0
Views: 69
Reputation: 25126
try this:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
options = ["option 1", "option 2", "option 3", "option 4"]
for i in range(len(options)):
print(alphabet[i] + " " + options[i])
it prints
a option 1
b option 2
c option 3
d option 4
Upvotes: 0
Reputation: 178
Instead of trying to slice the alphabet, you can just zip those iterables. It will only zip so many entries how many are in the smaller iterable.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
options = ["option 1", "option 2", "option 3", "option 4"]
for (letter, opt) in zip(alphabet, options):
print(letter, opt)
Note: that approach will work only for options iterables being smaller or equal to 26 entries. If you had more choices, you could use itertools.cycle
, but then you would have multiple options with the same letter, so just adding more unique characters to alphabet
or changing it to numbers, could solve that problem.
Upvotes: 0
Reputation: 21
You're iterating through the items of the list, not an index.
You can try this:
for i, element in enumerate(options):
print(choices[i], element)
Upvotes: 2
Reputation:
The issue is, that you're iterating over the elements of options
which are strings (option1, ...). You have to iterate over the length of your list.
for i in range(len(options)):
print(choices[i], options[i])
Upvotes: 2