Skip to content

#105: Multiply Strings in Python

While working through a Pluralsight course I noticed a strange looking command that seams to make no sense: '-' * 100. As it turns out, we can multiply strings in Python and this provides some nice amenities for our cli applications.

Multiplying strings?

Multiplying numbers is something basic that all programming languages offer, and Python is no exception:

>>> 5 * 20
100

However, in Python we can replace one part of the multiplication with a string and it still works:

>>> 3 * 'a'
'aaa'

If we want to create a line of – to split parts of the output in a Python script, we can write this call to print():

>>> print("-" * 75)
---------------------------------------------------------------------------

Conclusion

I find string multiplications a surprisingly usable feature and it will reduce a lot of typing when I need to print a separator for my cli tools.