How to repeat characters in Python without string concatenation?

I am currently writing a short program that performs frequency analysis. However, there is one line that bothers 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 doing it in the most pythonic way.

+5
source share
1 answer

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

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

And for your example, I would probably use:

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

Source: https://habr.com/ru/post/1216363/


All Articles