Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Things That Count Basic Numbers

Bill McKenna
Bill McKenna
586 Points

Printing String X amount of times.

When we use the code print(input_string*int(input_int)) before running it I would have assumed we would get and error because we are trying to multiply a string times an integer. How does python know that we are just looking to print it x amount of times. x being Int(input_int)

2 Answers

Dan Johnson
Dan Johnson
40,532 Points

The str object in Python defines the __mul__ method which which effectively overloads the multiplication operator. Defining __mul__ lets you do stuff like this:

class Message:
    def __init__(self, message):
        self.message = message

    def __mul__(self, operand):
        repeated_message = ""

        for i in range(1, operand+1):
            repeated_message += str(i) + ": " + self.message

        return repeated_message

msg = Message("Overloading the multiplication operator.\n")
print(msg * 5)

Will display:

1: Overloading the multiplication operator.
2: Overloading the multiplication operator.
3: Overloading the multiplication operator.
4: Overloading the multiplication operator.
5: Overloading the multiplication operator.

Here's a list of special method names from the documentation.

Bill McKenna
Bill McKenna
586 Points

Thanks Dan for the help

Following on from Dan Johnson 's excellent info, if you run Python in a console/terminal and enter the following command:


...you'll see how the str class/object implements the __mul__ method.

Try the following command to see a list of other built-in methods that the str object has: