How do I repeat a string in Python?

6

The question is simple: How do I repeat a string in Python?

I'm used to PHP.

When I want to repeat a string in PHP, I do so:

var $str = 'StackOverflow';
str_repeat($str, 5); 
// Imprime: StackOverflowStackOverflowStackOverflowStackOverflowStackOverflow

I tried this:

'StackOverflow'.repeat(5);

However an error is returned:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'repeat'
    
asked by anonymous 13.08.2015 / 13:56

2 answers

6

Just multiply the desired string.

a = 'StackOverflow'
print (a * 5)

return will be:

'StackOverflowStackOverflowStackOverflowStackOverflowStackOverflow'
    
13.08.2015 / 13:59
8

Is this enough for you?

str = 'StackOverflow'
print ((str[:13] + ' ') * 5)

See working on ideone .

The repetition occurs with the multiplication operator . Many criticize the operator overload for use with strings , but if you think about it, it makes sense.

You can get a snippet of string using the < in> slice , that is, it takes a part of string which is nothing more, roughly, than an array character.

    
13.08.2015 / 14:04