[Tutor] printing items form list

Mats Wichmann mats at wichmann.us
Fri Mar 3 11:52:08 EST 2017


On 03/03/2017 05:12 AM, Rafael Knuth wrote:
> I want to print individual items from a list like this:
> 
> You have a book, towel, shirt, pants in your luggage.
> 
> This is my code:
> 
> suitcase = ["book", "towel", "shirt", "pants"]
> print ("You have a %s in your luggage." % suitcase)
> 
> Instead of printing out the items on the list, my code appends the
> list to the string. How do I need to modify my code?
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py ==
> You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.


By way of explanation:

suitcase = ["book", "towel", "shirt", "pants"]
print(type(suitcase))
print ("You have a %s in your luggage." % suitcase)


===
<class 'list'>
You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.

suitcase is a list.  You explicitly ask for it to be shown a string with
"%s", so the list class's string representation method is called to
produce what the class thinks is the best way to show what the list
contents looks like.  that conversion to a string someone else's idea
(Python default), but not what you wanted, though; joining with commas
is the right choice based on what you said you wanted.




More information about the Tutor mailing list