Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"While passing a single value to string formatting works, it's dangerous and can fail in subtle ways". AKA Python design errors.


> it's dangerous and can fail in subtle way

The only subtle way it fails, which I can think of is:

    In [27]: foo = (1,2)

    In [28]: '%s' % foo
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    ----> 1 '%s' % foo

    TypeError: not all arguments converted during string formatting


And, that's easy to fix:

   '%s' % (foo,)
Ugly, but you can be safe if you don't mind three more bytes of source code.


Or '{}'.format(foo). Personally, I have never faced this issue as:

1. I know/control the input while string formatting.

2 String-formatting tuple comes up rarely.


I format tuples for debugging on a regular basis, but tend to just wrap every arg to the format string in repr, so this never comes up.


This won't solve the immediate problem, but if you use "%r" instead of "%s", python will do the repr() for you.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: