Is there a shorthand method to repeat a string multiple times?


We can use concatenation to create a string that repeats multiple times by adding itself over and over, but this may become tedious for many repetitions. Is there a shorthand method to repeat a string multiple times?


In Python, we can do this using the * operator, and essentially multiplying a string by the number of times it should repeat in a newly created string.

Example code

message = "Hi there! "
message_x3 = message * 3

# message_x3 would equal:
# "Hi there! Hi there! Hi there! "

That is really cool, no loops.


The strings are repeating multiple times but with no space between the last word and first word of next string. How can be make space in case of repeating a string multiple lines. One string per line

1 Like

In the given example double check the contents of the string that is saved to message. A space is a character.
If you wanted a new line each time the newline chracter is “\n”. Bear in mind these methods will print with a trailing space and a trailing newline respectively.


Is there any loop I can write to print out serially named objects? Sorry if my phrasing sounds wrong.
Suppose I have message=string1+string2+string3+string4+string5+string6 and so on till string 17 (as part of some random exercise haha) and string1 to string17 have been predefined.

How can I rewrite message in form of a loop (if I don’t want to type string1, then string2, then string3… and so on)?

Whilst there are methods to do this they’d probably be frowned upon. I think the best option would be to refactor your earlier code so that you don’t end up with numerous similarly named variables. Add them to a different data type (e.g. a list) and it’ll make the overall program both easier to read and easier to deal with.

1 Like

That is really good!!

How is the newline character,"\n",applied?

Applied in what way? So far as Python’s concerned (at least Python3) it’s just a unicode value.

The output side of this is a bit complex with platform differences and text encodings but most of the time you don’t need to worry about it. It should be written out in a way so as to appear as an actual newline for your system.

As a very simple example-

print("text\ntext on a new line")
text on a new line
1 Like

I understand now. Thanks for your help!


Is there a way to print multiple lines with different variables without having to repeat typing print?
For example,
#Assign variables
a = 0
b = 1
c = 2
print(str(a) \n str(b) \n str(c))

I tried “\n” but it did not working

The standard route we be to use some kind of string formatting, either .format or f-strings. I’m sure they’ll be introduced soon enough in the course.

1 Like

print(a,"\n", b, “\n”, c)
This will print with leading space before 1 and 2 as “,” in print functions inserts a space in between: