11

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.

Spaxxy
  • 171
  • 1
  • 2
  • 6

1 Answers1

20

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)
David Wolever
  • 148,955
  • 89
  • 346
  • 502