Avoid use + to format strings
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
Old-style
New-style
What to use?
Common patterns
s
— stringd
— digitf
— floatb
— binaryx
— hexadecimalX
— HEXADECIMALo
— octal%
— to quote a %
symbolOld-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
'%(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
Вам ответят команда поддержки Хекслета или другие студенты.
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
Наши выпускники работают в компаниях:
Зарегистрируйтесь или войдите в свой аккаунт