Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate lines in Python

Tags:

python

string

I have print (5*"@"), which gives me:

@@@@@

Now if I add \n to it, print (5*"@\n"), it gives me five lines consisting of one @ each.

What do I do when I want it to give me this:

Four lines consisting of five @ each without having to type @@@@@ in the code?

I tried something like print(5*"@", 4*"\n") but it obviously didn't work.

like image 906
Raphael Calvin Pettersson Avatar asked Nov 23 '25 02:11

Raphael Calvin Pettersson


2 Answers

You can use the following:

(5 * '@' + '\n') * 4

Note that this is much less clear than '@@@@@\n' * 4.

like image 158
Andrew Clark Avatar answered Nov 25 '25 16:11

Andrew Clark


How about you loop over the print statement 4 times?

for _ in range(4):
    print(5 * '@')

Or, use + to append the newline, and multiply the result by 4:

print((5 * '@' + '\n') * 4)

Or, use a list and .join() the elements with newlines:

print('\n'.join([5 * '@'] * 4))
like image 33
Martijn Pieters Avatar answered Nov 25 '25 16:11

Martijn Pieters