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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With