3 ms·
I tend to use the old style ("%s" % "lel"). Just wondering, does this affect that too?
by libeclipse 10y ago
I tend to use the old style ("%s" % "lel"). Just wondering, does this affect that too?
- antsar 10y agoAttribute access doesn't seem to work with old-style formatting, so I would think it's safe. >>> class foo: ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... >>> my_foo = foo(secret="bazinga") >>> >>> "%(foo)s" % {'foo': my_foo} '<__main__.foo instance at 0x1101d23f8>' >>> >>> "%(foo.secret)s" % {'foo': my_foo} Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'foo.secret'
- bubblesocks 10y agoThe nice thing about the new format is that you can reverse the order of the variables inside the string, which is nice when you're localizing strings into languages with a reversed sentence structures, like Japanese. I haven't done a ton of Python, but the old style won't let you do that, will it?
- Franciscouzo 10y agoReversing the order is not possible, but you can use a dict instead: >>> "%(foo)s" % {"foo": "bar"} 'bar'
- libeclipse 10y agoHeyyyyyy I did not know that. TIL, thank you.
- dozzie 10y agoFunny. I thought Python implemented all the quirks of the original printf() formatting, including using arguments at specific positions. Apparently it didn't (and arguably it's a good thing). $ printf '%2$s %2$s %1$s\n' aaa bbb bbb bbb aaa
- nitely 10y agoYes, it will, just use named placeholders: "%(some)s" % {'some': 'helllo'}
- tedmiston 10y agoI'm not sure I understand the use case for reversing the formatting variables, but you could do this to make old-style formatting work that way: >>> 'hello, %s %s' % tuple(reversed(['smith', 'bob'])) 'hello, bob smith' I think it's more readable if you abstract that bit into a lambda function: >>> rev_args = lambda *args: tuple(reversed(args)) >>> 'hello, %s %s' % rev_args('smith', 'bob') 'hello, bob smith'