user1165419 user1165419 - 3 months ago 9
Python Question

print full item in multiple lists

I'm trying to print two lists, but it only prints the first letter of each item in the lists;

lst1 = ['hello', 'hi', 'sup']
lst2 = ['bye', 'cya', 'goodbye']

for item in [lst1, lst2]:
print 'Your options are: ' + ' '.join(['-{0}'.format(*x) for x in item])


Result;

You can choose: -h -h -s
You can choose: -b -c -g


How do I print the string in full?

Answer

Removing * from format will work for you:

>>> for item in [lst1, lst2]:
...     print 'Your options are: ' + ' '.join(['-{0}'.format(x) for x in item])
... 
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye

Explaination: *my_list unpacks the list. Since, string is also a list of chars, '-{0}'.format(*x) will become: '-{0}'.format(['h', 'e', 'l', 'l', 'o']). Hence, it is just inserting the string at the 0th index of ['h', 'e', 'l', 'l', 'o'] i.e. h.

Comments