Asterisk symbol in Python

I studied various ways to approach the classic FizzBuzz problem and came across this:

for i in xrange(1, n+1):
    print "Fizz"*(i%3 == 0) + "Buzz"*(i%5 == 0) or i

Are asterisks abbreviated for the operator if? If so, are these designations specific to print?

Thanks in advance.

+4
source share
2 answers

An asterisk in Python is actually the standard multiplication operator *. It displays the method of the __mul__object it worked on, and therefore can be overloaded to have custom values. This has nothing to do with ifor print.

(str unicode) /, , "foo" * 5 "foofoofoofoofoo".

>>> 'foo' * 5  # and the other way around 5 * "foo" also works
'foofoofoofoofoo'

"Fizz" * (i % 3 == 0) "" :

"Fizz" if i % 3 == 0 else ""

, i % 3 == 0 , boolean - Python, True == 1 False == 0, , "" , ' , .

.. , / Python - ( , ), ( , , , . http://pastebin.com/Q92j8qga ( , PyPy: http://pastebin.com/sJtZ6uDm)).


* list tuple:

>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

* , Python:

class Foo(object):
    def __mul__(self, other):
        return "called %r with %r" % (self, other)

print Foo() * "hello"  # same as Foo().__mul__("hello")

:

called <__main__.Foo object at 0x10426f090> with 'hello'

*, __mul__, "" , int, float , 3 * 4 (3).__mul__(4) ( ). int *:

class MyTrickyInt(int):
    def __mul__(self, other):
        return int.__mul__(self, other) - 1
    def __add__(self, other):
        return int.__add__(self, other) * -1

print MyTrickInt(3) * 4  # prints 11
print MyTrickyInt(3) + 2  # prints -5

... , , :) ( , !)

+9

asterik python. , . ,

print "test"*0
print "test"*1
print "test"*2

:

<blank line>
test
testtest

or, :

print "Fizz"*(i%3 == 0) + "Buzz"*(i%5 == 0) or i 

Fizz Buzz Non zero/True, python i

Fizz True, 3 ( 3 i, 3) , Buzz 5 . Fizz Buzz , 15. i , False.

+1

Source: https://habr.com/ru/post/1536269/


All Articles