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

Question

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?

Answer

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! "
31 Likes

That is really cool, no loops.

18 Likes

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.

4 Likes

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
text on a new line

I understand now. Thanks for your help!

2 Likes