How to print a string multiple times? [closed]
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this questionHow 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.
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)
for i in range(3):
print "Your text here"
Or
for i in range(3):
print("Your text here")
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.
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.
EDIT: Old answer erased in response to updated question.
You just store the string in a variable:
separator = "!" * int(raw_input("Enter number: "))
print separator
do_stuff()
print separator
other_stuff()
print separator
rows = int(input('How many stars in each row do you want?'))
columns = int(input('How many columns do you want?'))
i = 0
for i in range(columns):
print ("*" * rows)
i = i + 1
The question is a bit unclear can't you just repeat the for loop?
a=[1,2,3]
for i in a:
print i
1
2
3
for i in a:
print i
1
2
3
def repeat_char_rows_cols(char, rows, cols):
return (char*cols + '\n')*rows
>>> print(repeat_char_rows_cols('@', 4, 2))
@@
@@
@@
@@
For example if you want to repeat a word called "HELP" for 1000 times the following is the best way.
word = ['HELP']
repeat = 1000 * word
Then you will get the list of 1000 words and make that into a data frame if you want by using following command
word_data =pd.DataFrame(repeat)
word_data.columns = ['list_of_words'] #To change the column name
n=int(input())
w=input()
print(f'{w}\n'*n)
# this will print the word(w) , n times in separte lines
精彩评论