How do I repeat a string in Python?

Asked

Viewed 5,604 times

7

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 that:

'StackOverflow'.repeat(5);

But an error is returned:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'repeat'

2 answers

7

  • Why of :13?

  • You take the part you want to repeat.

  • o. O! That’s cool! To do this in PHP I would have to use the substr and str_replace chained! Python is very simple

  • 1

    I put it in a way that works in Python 3 as well. What I like about the language is that it tries most of the time to actually make the codes smaller, simpler.

6


Just multiply the desired string.

a = 'StackOverflow'
print (a * 5)

the return will be:

'StackOverflowStackOverflowStackOverflowStackOverflowStackOverflow'
  • 1

    In that case, the *=5 will change the value directly in a. So I’d have to just do a * 5 if I wanted the value to repeat without changing the original variable?

  • 2

    'StackOverflow' * 5 directly also serves.

  • @Wallacemaxters, exact. I’ll edit my answer to make it clearer.

  • I think posting these variations in the answers can enrich the knowledge :), just a tip

Browser other questions tagged

You are not signed in. Login or sign up in order to post.