Зарегистрируйтесь для доступа к 15+ бесплатным курсам по программированию с тренажером

Форматирование строк Введение в Python

Видео может быть заблокировано из-за расширений браузера. В статье вы найдете решение этой проблемы.

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': 'ivan@test.com',
       'registered_at': '2015-12-31'}
>>> 'User Ivan registered with email <ivan@test.com> 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='john@test.com', age=42)
'User {user[name]} <{user[email]}>, age {user[age]:d}'.format(user=user)
>>> 'User John <john@test.com>, 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

Аватары экспертов Хекслета

Остались вопросы? Задайте их в разделе «Обсуждение»

Вам ответят команда поддержки Хекслета или другие студенты.

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно

  • 130 курсов, 2000+ часов теории
  • 1000 практических заданий в браузере
  • 360 000 студентов
Отправляя форму, вы принимаете «Соглашение об обработке персональных данных» и условия «Оферты», а также соглашаетесь с «Условиями использования»

Наши выпускники работают в компаниях:

Логотип компании Альфа Банк
Логотип компании Aviasales
Логотип компании Yandex
Логотип компании Tinkoff

Используйте Хекслет по-максимуму!

  • Задавайте вопросы по уроку
  • Проверяйте знания в квизах
  • Проходите практику прямо в браузере
  • Отслеживайте свой прогресс

Зарегистрируйтесь или войдите в свой аккаунт

Отправляя форму, вы принимаете «Соглашение об обработке персональных данных» и условия «Оферты», а также соглашаетесь с «Условиями использования»