How to repeat characters in Python without string concatenation?

Spaxxy picture Spaxxy · Mar 28, 2015 · Viewed 14.3k times · Source

I'm currently writing a short program that does frequency analysis. However, there's one line that is bothering me:

"{0[0]}  | " + "[]" * num_occurrences + " Total: {0[1]!s}"

Is there a way in Python to repeat certain characters an arbitrary number of times without resorting to concatenation (preferably inside a format string)? I don't feel like I'm doing this in the most Pythonic way.

Answer

David Wolever picture David Wolever · Mar 28, 2015

The best way to repeat a character or string is to multiply it:

>>> "a" * 3
'aaa'
>>> '123' * 3
'123123123'

And for your example, I'd probably use:

>>> "{0[0]}  | {1} Total: {0[1]!s}".format(foo, "[]" * num_occurrences)