Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
"Good morning, %(first)s %(last)s" % {'first':'Reuven', 'last':'Lerner'}>>> "int {varname}[] = {{a, b, c, d}}".format(varname="test")
'int test[] = {a, b, c, d}'
>>> "int %(varname)s[] = {a, b, c, d}" % dict(varname="test")
'int test[] = {a, b, c, d}'
>>> class Wrap(object):
... def __init__(self, inner):
... self.inner = inner
... def __getattr__(self, attr):
... if '(' in attr:
... return eval('this.' + attr, {}, {'this': self.inner})
... return getattr(self.inner, attr)
...
>>> "{d.get('b', 'default')}".format(d=Wrap({'a': 42}))
'default'
%. Это немного насторожило, всё-таки стандартная библиотека. И вот что интересно, в документации к Python 3.2. говорится, что SinceОднако, документация Python 3.4 выглядит немного по-другому:str.format()is quite new, a lot of Python code still uses the%operator. However, because this old style of formatting will eventually be removed from the language,str.format()should generally be used.
The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.
% — только для простейших случаев, вроде "...%s..." % var.>>> class C(object):
foo = 1
def __format__(self, spec):
if spec == 'yes':
return 'format done'
else:
return str(self.foo)
>>> c = C()
>>> "{}, {:yes}".format(c, c)
'1, format done'
Учим старую собаку новым трюкам или как я научился любить str.format и отказался от %