Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - print "x" "y" times when passed in a list of [x,y]

Tags:

python

list

python n00b here doing the pythonchallenge, stuck on middle of a level right now.

ex: ([' ', 10], ['#', 20])

How do I print space 10 times with python? I've tried many things, but none worked...

Thanks!

edit: I'm not looking to learn how to use for-loops, but rather, list-manipulation(is that what they're called?) techniques that i can use to print a list with any value as the first element.... thanks for the replies though!

like image 636
JBS Avatar asked Feb 06 '11 10:02

JBS


2 Answers

print ' ' * 10

Same as you would for any other character, e.g.

print 'a' * 10

So for your list, assuming it's called l:

for c, n in l:
    print c * n
like image 193
Mikel Avatar answered Sep 21 '22 02:09

Mikel


In Python you can multiply a string by an integer to get a repeated version of the string:

>>> mystring = ' ' * 10
>>> mystring
'          '

Obviously, you can print the result of the expression directly:

>>> print '#' * 20
####################

This also works for tuples and lists:

>>> (1,2,3) * 2
(1, 2, 3, 1, 2, 3)
>>> ['a','b','c'] * 3
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
like image 36
Dave Webb Avatar answered Sep 19 '22 02:09

Dave Webb