Если видео недоступно для просмотра, попробуйте выключить блокировщик рекламы.

###Format strings in Python

Avoid use + to format strings

  • Use + operator to concatenate only short strings...
  • ...because of performance issues
  • Multiple + is ugly
  • It creates lots of str in memory
title = 'The best site'
link = 'http://fake.url'
print '<a href="' + link + '">' + title + '</a>'
>>> <a href="http://fake.url">The best site</a>

Two ways to format a string

  • C-style, % operator (old)
  • C#-style, .format method (new)

Old-style

  • A little bit faster
  • Suitable for those who like C/C++
  • Uses tuple/dict as parameters

New-style

  • A little bit slower
  • Uses *args, **kwargs as parameters
  • More complex, it's a mini-language
  • You can access nested data
  • Common in Py3
  • Has extra features in Py3

What to use?

  • It depends on the context
  • It depends on the style guides

Common patterns

  • s — string
  • d — digit
  • f — float
  • b — binary
  • x — hexadecimal
  • X — HEXADECIMAL
  • o — octal
  • % — to quote a % symbol

Old-style examples

%<spec><type> — unnamed %.2f

%(<name>)<spec><type> — named %(price).2f

'%10s' % 'test'           '      test'
'%10d' % 42               '        42'
'%010d' % 42              '0000000042'
'%10.2f' % 42.555555555   '     42.56'
'%010.2f' % 42.555555555  '0000042.56'

'%s was 1st, %s was 2nd' % ('Ivan', 'John')
>>> 'Ivan was 1st, John was 2nd'

'%x' % 10        'a'
'%x' % 106500    '1a004'
'%X' % 999       '3E7'
'%e' % 10.22     '1.022000e+01'
'%o' % 100500    '304224'

'Your result is %d%%' % 99
'Your result is 99%'

Use dicts to

  • use parameters many times
  • make your template more readable
'%(val)5s, %(val)05d, %(val)05.2f, %(val)x' % {'val': 42}
>>> '   42, 00042, 42.00, 2a'

tpl = 'User %(username)s registered with email <%(email)s> at %(registered_at)s'
tpl % {'username': 'Ivan', 'email': 'iv[email protected]',
       'registered_at': '2015-12-31'}
>>> 'User Ivan registered with email <[email protected]> at 2015-12-31'

New-style examples {<index>:<spec>} — unnamed {0:+0.3f}

{<name>:<spec>} — named {price:+0.3f}

# new-style examples
# {<field>:<spec>}  is a common template

'{0} {1} {2}'.format('foo', 42, True)       'foo 42 True'
'{2} {1} {0} {2}'.format('foo', 42, True)   'True 42 foo True'
'{} {} {}'.format(1, 2, 3, 4, 5)            '1 2 3'

data = {'foo': 42, 'bar': 999}
'{foo} {bar}'.format(**data)                '42 999'

class Point:
    lat = 32.634345735
    lon = -54.62462344

'Your position is {0.lat:+0.3f} {0.lon:+0.3f}'.format(Point())
'Your position is +32.634 -54.625'

user = dict(name='John', email='[email protected]', age=42)
'User {user[name]} <{user[email]}>, age {user[age]:d}'.format(user=user)
>>> 'User John <[email protected]>, age 42'

'{:,}'.format(1100500)
'1,100,500'

'{value:b}'.format(value=123456)
'11110001001000000'

for x in [234, 100500, 4634.234]:
    print '{0:.>20.2f}'.format(x)

'..............234.00'
'...........100500.00'
'.............4634.23'

for x in ['Title', 'Subtitle', 'Chapter']:
    print '{0:~^20}'.format(x)

'~~~~~~~Title~~~~~~~~'
'~~~~~~Subtitle~~~~~~'
'~~~~~~Chapter~~~~~~~'

Remember about str/unicode coerce

class Obj(object):
    def __str__(self):
        return 'str obj'
    def __unicode__(self):
        return u'unicode obj'

'%s' % Obj()
>>> 'str obj

'u'%s' % Obj()
>>> u'unicode obj'

Summary

  • There are two ways to format a string
  • The old one is faster and shorter
  • The new one has extra features
  • Use those what you want
  • Practice
Мы учим программированию с нуля до стажировки и работы. Попробуйте наш бесплатный курс «Введение в программирование» или полные программы обучения по Node, PHP, Python и Java.

Хекслет

Подробнее о том, почему наше обучение работает →