#1
  1. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481

    Non-commuting string multiplication


    Code:
    $ python -c 'print("%d"%2*3)'
    222
    $ python -c 'print(3*"%d"%2)'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: not enough arguments for format string
    In hanoi thread I wrote
    Code:
    self.fmt = '{:4d}:'+('  ({:%ds})'%self.n)*3
    knowing that the bold parenthesis were unneeded. Does the multiplication operation commute without them? No!

    Code:
    $ python -c 'print(3*"%d")'
    %d%d%d
    [edit]oh well, multiplication doesn't commute with modulus either.
    Code:
    $ python -c 'print(5%6*3)'
    15
    $ python -c 'print(3*5%6)'
    3
    [/edit]
    Last edited by b49P23TIvg; February 17th, 2014 at 11:02 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    438
    Rep Power
    67
    Strange. A good reason (excuse?) if any to use new-style formatting with .format()

    Code:
    >>> 3 * '{0}'.format(2)
    '222'
    >>> '{0}'.format(2) * 3
    '222'

    Comments on this post

    • b49P23TIvg agrees : good point, this gives favorable precedence.
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (work laptop), Trisquel GNU/Linux 6.0.1 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)

IMN logo majestic logo threadwatch logo seochat tools logo