how to print variable few time?
Steve D'Aprano
steve+python at pearwood.info
Sat Nov 12 08:55:56 EST 2016
On Sat, 12 Nov 2016 11:58 pm, guy asor wrote:
> hello!
>
> this is my code:
>
> word=raw_input()
> print word*3
>
>
> with this code im getting - wordwordword.
> what changes i need to make to get - word word word - instead?
Lots of ways! Here is the simplest, but longest. Call print three times,
being careful to not allow a newline to be printed until the end:
print word, # note the comma, that suppresses the new line
print word,
print word # no comma
What if you wanted to print it fifty times? Use a loop.
for i in range(50):
print word, # note the comma
# At the end of the loop, print a blank to get a new line.
print
Here's a nice trick that's a bit more mysterious for beginners, but works
well:
print ' '.join([word]*3)
If you don't understand it, break it up into each piece:
[word]*3 creates a list [word, word, word]
' '.join(the list) makes a string with the words separated by spaces:
' '.join(['quick', 'brown', 'fox']) => 'quick brown fox'
and then you finally print the result.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list