Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat characters in Python without string concatenation?

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.

like image 414
Spaxxy Avatar asked Mar 28 '15 19:03

Spaxxy


People also ask

How do you repeat a character in Python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.

How do you double every character in a string Python?

Take the input string and store it in a variable. Loop through the string using a for loop, multiply every character by 2 , and add the resulting character to an output variable holding an empty string initially. This will double every character and add all the resulting characters to form an expected output string.

Is there a repeat function in Python?

Python NumPy repeat() function is used to repeat the individual elements of an array a specified number of times. Specify the number of times to repeat by the repeats parameter.

How do I print the same character multiple times in Python?

Using the * operator to print a character n times in Python In the print() function we can specify the character to be printed. We can use the * operator to mention how many times we need to print this value. See the code below. In the above example, we printed the character five times using the * operator.


1 Answers

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)
like image 143
David Wolever Avatar answered Oct 13 '22 22:10

David Wolever