Search code examples
pythonpython-3.xargumentsseparator

Using sep when multiplying strings in Python


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?


Solution

  • 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).