[Tutor] Printing a list without square brackets, was Re: Hi Tutor
Peter Otten
__peter__ at web.de
Sat Jan 9 16:36:49 EST 2016
yehudak . wrote:
> I wrote this short program for my grandson:
Nothing against a little help here and there, but solving a problem can be
fun, and you are taking away some of that fun.
Does your grandson speak English? You might encourage him to post here
himself. We bite, but only grandpas ;)
> from random import sample
>
> soups = ['Onion soup', 'Veggie soup', 'Chicken soup', 'Corn soup']
> salads = ['Veggie', 'Onion', 'Cabbage', 'Lettuce', 'Caesar', 'Tomato']
> main = ['Crab cake', 'Catfish', 'Ribs', 'Chopped liver', 'Meat balls']
> beverage = ['Wine', 'Rum', 'Lemonade', 'Red bull', 'Margarita', 'Jin']
>
> def dish(soups):
> return (sample(soups, 1))
>
> print('Soup:\t\t', dish(soups))
> print('Salad:\t\t', dish(salads))
> print('Main dish:\t', dish(main))
> print('Beverage:\t', dish(beverage))
>
> A possible output could be:
>
> Soup: ['Chicken soup']
> Salad: ['Caesar']
> Main dish: ['Meat balls']
> Beverage: ['Wine']
>
> How do I get rid from the square brackets and the quotation marks in the
> output?
random.sample(items, n) returns a list of length n. As your sample size is
one you could use random.choice(items) instead.
>>> import random
>>> soups = ['Onion soup', 'Veggie soup', 'Chicken soup', 'Corn soup']
>>> print("Soup:", random.choice(soups))
Soup: Chicken soup
When you actually want to print multiple strings you can preprocess the list
with the str.join() method:
>>> print("Two soups:", ", ".join(random.sample(soups, 2)))
Two soups: Veggie soup, Chicken soup
More information about the Tutor
mailing list