Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a string multiple times? [closed]

Tags:

python

How can I repeat a string multiple times, multiple times? I know I can use a for loop, but I would like to repeat a string x times per row, over n rows.

For example, if the user enters 2, the output would be:

@@
@@
@@
@@

Where x equals 2, and n equals 4.

like image 536
user718531 Avatar asked Jun 09 '11 13:06

user718531


People also ask

How do I print 10 times a word in Python?

How do you print a string 10 times in Python? Use range() to print a string multiple times Use range(stop) to create a range of 0 to stop where stop is the number of lines desired. Use a for-loop to iterate through this range.

How do you repeat a string multiple times in Python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.

How do I print the same character multiple times in Python?

Using the * operator to print a character n times in Python In the print() function we can specify the character to be printed. We can use the * operator to mention how many times we need to print this value.


4 Answers

If you want to print something = '@' 2 times in a line, you can write this:

print(something * 2)

If you want to print 4 lines of something, you can use a for loop:

for i in range(4):
     print(something)
like image 153
Serg Avatar answered Oct 08 '22 18:10

Serg


So I take it if the user enters 2, you want the output to be something like:

!!
!!
!!
!!

Correct?

To get that, you would need something like:

rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")

for i in range(rows):
    print "!" * times_to_repeat

That would result in:

How many times to repeat per row?
>> 4
!!!!
!!!!
!!!!
!!!!

I have not tested this, but it should run error free.

like image 25
Josh Hunt Avatar answered Oct 08 '22 17:10

Josh Hunt


It amazes me that this simple answer did not occur in the previous answers.

In my viewpoint, the easiest way to print a string on multiple lines, is the following :

print("Random String \n" * 100), where 100 stands for the number of lines to be printed.

like image 42
Timbus Calin Avatar answered Oct 08 '22 19:10

Timbus Calin


for i in range(3):
    print "Your text here"

Or

for i in range(3):
    print("Your text here")
like image 45
JAB Avatar answered Oct 08 '22 18:10

JAB