开发者

Python - concatenate a string to itself, multiple times [duplicate]

开发者 https://www.devze.com 2023-03-16 19:45 出处:网络
This question already开发者_JAVA百科 has answers here: How to repeat a string with spaces? (6 answers)
This question already开发者_JAVA百科 has answers here: How to repeat a string with spaces? (6 answers) Closed 5 months ago.

Suppose I have a string my_string = "I am good."

How can I get a string that contains three copies of my_string, with spaces in between? Would it be something like str.join(' ',my_string*3)?


You're pretty close. Try this:

>>> my_string = "I am good."
>>> " ".join([my_string]*3)
'I am good. I am good. I am good.'

You need [my_string]*3 instead of my_string*3 because you want a list containing the string three times (that can then be joined) instead of having a single big string containing the message three times.

Also, " ".join(a) is shorthand for str.join(" ", a).


This should work:

" ".join((my_string,) * 3)


" ".join([my_string for i in range(3)]


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


Or you can just take advantage of the fact that multiplying a string concatenates copies of it: add a space to the end of your string and multiply without using join.

>>> my_string = "I am good."
>>> (my_string+' ')*3
'I am good. I am good. I am good. '
0

精彩评论

暂无评论...
验证码 换一张
取 消