Issues with printing the same string multiple times

Hi all the wonderful people out there. I am new to python programming and still struggling to learn it.
I wanted to print a string 10 times with a single line of code. I did the following:
var1="Hello World " - Hello World is defined as var1

print(10*‘Hello World’) - Text Hello World is printed 10 times in a straight line

print(10*‘Hello World\n’) - Text Hello World is printed 10 times vertically on separate lines

print(10*var1) - Text Hello World is printed 10 times in a straight line

print(10* ‘var1\n’) - word var1 is printed 10 times vertically not Hello World while var1 refers to the variable Hello World

I wanted to print the string value stored in var1 a total of 10 times vertically using the \n command. However I am getting he text var1 rather than the value of var1.

This almost does what you want. It is missing the “\n” at the end of the content of var1. Lets add it:

>>> var1 = "Hello world"
>>> print(10*(var1 + "\n"))
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world

>>>

Hi Arshad,

\n isn’t a command – it is a special escape code for newlines. It
only works inside a string: outside of a string it is a syntax error.

When you put var1 inside quotation marks, like this:

"var1"

is no longer refers to the variable, it is just a string like
“Hello World”.

What you can do is concatenate a newline to the variable var1, then
repeat it ten times:

var1 = "Hello World"
print(10*(var1 + "\n"))

Notice that we need round brackets (parentheses) to ensure that the
concatenation occurs before the repeat. If you write this:

print(10*var1 + "\n")

the string “Hello World” will be repeated 10 times, and then a single
newline will be concatenated.

One problem with this method is that there is an extra newline at the
end which you might not want. Instead we can do this:

print("\n".join([var1]*10)

What this does is:

  • [var1] constructs a list containing “Hello World”

  • [var1]*10 replicates that ten times, equivalent to:

    [var1, var1, var1, var1, var1, var1, var1, var1, var1, var1]

  • "\n".join(...) joins those ten strings together with newlines
    between the items.

  • And finally print(...) does the actual printing.

Here’s another way that we can print something ten times:

for i in range(10): print(var1)