Python - concatenate a string to itself, multiple times

Viewed 12347

I want to join strings my_string = "I am good." such that it should be printing the same my_string 3 times, as in my_string*3 with a space in between each full sentence. How do I do it? something like str.join(' ',my_string*3)?

I know this a basic question, but I want to know this.

Thank you in advance, Sammed

5 Answers

I ran some perfomance checks, to see how different methods compete with each other.

import time

def forLoop(s):
  start = time.time()
  z = ""
  for i in range(ITERS):
    z += s
  return time.time()-start

def listJoin(s):
  start = time.time()
  "".join([s]*ITERS)
  return time.time()-start

def strMultiply(s):
    start = time.time()
    s*ITERS
    return time.time()-start

ITERS = 10000
my_string = "I am good."
a, b, c = 0, 0, 0
for i in range(ITERS):
    a += forLoop(my_string)
    b += listJoin(my_string)
    c += strMultiply(my_string)

print("For loop:", a)
print("List join:", b)
print("String multiplication:", c)

Output:

For loop: 5.720043182373047
List join: 0.8931441307067871
String multiplication: 0.025591611862182617
Related