3

I've been told that in python 3.x it's possible to add a separator between strings that you repeat using multiplication, for example..

c = "rabble"

print(c * 5, sep = ' | ')

I would like it to print out "rabble" 5 times with the string | in between each repeat.

It keeps printing the repeated string, but without the separator character. I'm having trouble finding info regarding the use of sep in this specific situation. What am I doing wrong?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160

2 Answers2

4

You can get the effect you want, but it doesn't really have much to do with multiplication per se.

The sep argument to print() provides a separator between the non-keyword arguments - for example:

>>> print("spam", "eggs", "ham", sep=" | ")
spam | eggs | ham

You could just pass c to print() 5 times to get the output you're looking for:

>>> c = "rabble"
>>> print(c, c, c, c, c, sep=" | ")
rabble | rabble | rabble | rabble | rabble

... but that's clunky, and no use if you don't know in advance how many times you'll want c to appear.

To get around this problem, you can use argument unpacking – a special syntax to pass a list or other sequence to a function as though the items in it were being passed as individual arguments:

>>> s = ["spam", "eggs", "ham"]
>>> print(*s)  # notice the *
spam eggs ham

To get the result you're looking for, you can construct a list on the fly from 5 copies of c, and pass that list with the argument unpacking notation:

>>> print(*([c] * 5), sep = ' | ')
rabble | rabble | rabble | rabble | rabble

Notice that you're multiplying a list containing c by five, rather than c itself. You might find it helpful to check out what print(*(c * 5), sep = ' | ') actually does, and to try and work out why (hint: strings are also sequences).

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 2
    Thanks Zero, I tried the code at the end (using argument unpacking without putting c in a list) and it prints out each letter of the string "rabble" with the '|' string separating each one. I think I have a better understanding of the original problem, which is that print(c*5) simply concatenates 5 strings and provides no breaking point into which the '|' string can be inserted. When using argument unpacking, each letter is its own item, and in lists each string is its own item between both of which a separator can be inserted. Thanks again. – wellthatdidn'twork Jan 20 '17 at 15:03
-1

Try something like this:

print("rabble | "*5)

Murali
  • 1