Are you over 18 and want to see adult content?
More Annotations
![A complete backup of thekomisarscoop.com](https://www.archivebay.com/archive5/images/564d0edf-dd6e-49ec-aaf9-d15d04bf568a.png)
A complete backup of thekomisarscoop.com
Are you over 18 and want to see adult content?
![A complete backup of synergy-project.org](https://www.archivebay.com/archive5/images/158b67d1-e55b-4a01-81ff-3e9019771e17.png)
A complete backup of synergy-project.org
Are you over 18 and want to see adult content?
![A complete backup of fungodoctor.com.ua](https://www.archivebay.com/archive5/images/3df66ff3-e534-483a-be11-c1865127057b.png)
A complete backup of fungodoctor.com.ua
Are you over 18 and want to see adult content?
Favourite Annotations
![A complete backup of https://skiresort.nl](https://www.archivebay.com/archive6/images/9c7b67bc-a55a-434f-b061-a753b7689544.png)
A complete backup of https://skiresort.nl
Are you over 18 and want to see adult content?
![A complete backup of https://lingoapp.com](https://www.archivebay.com/archive6/images/9805a949-7c19-4041-aa80-7c7431c1c0e4.png)
A complete backup of https://lingoapp.com
Are you over 18 and want to see adult content?
![A complete backup of https://hamerguitars.com](https://www.archivebay.com/archive6/images/ad731c07-f52b-4986-a7a0-df6396c9004f.png)
A complete backup of https://hamerguitars.com
Are you over 18 and want to see adult content?
![A complete backup of https://andymckee.com](https://www.archivebay.com/archive6/images/aba30ede-fc35-4b07-ad53-3ea3991d66f8.png)
A complete backup of https://andymckee.com
Are you over 18 and want to see adult content?
![A complete backup of https://100fang.com](https://www.archivebay.com/archive6/images/4e67b31d-ade0-4a54-8be3-914ad8f9b458.png)
A complete backup of https://100fang.com
Are you over 18 and want to see adult content?
![A complete backup of https://t3.co.uk](https://www.archivebay.com/archive6/images/a7e2ad5c-4883-4452-839e-5aca5ba664dd.png)
A complete backup of https://t3.co.uk
Are you over 18 and want to see adult content?
![A complete backup of https://versedskin.com](https://www.archivebay.com/archive6/images/426a636b-e99b-4fdf-9471-61da47ebbe31.png)
A complete backup of https://versedskin.com
Are you over 18 and want to see adult content?
![A complete backup of https://aist-d.ru](https://www.archivebay.com/archive6/images/2c34206a-f308-47af-a100-dadf020185b7.png)
A complete backup of https://aist-d.ru
Are you over 18 and want to see adult content?
![A complete backup of https://kealoans.com](https://www.archivebay.com/archive6/images/f773e2d5-ec14-477b-94db-8e9f5710adf6.png)
A complete backup of https://kealoans.com
Are you over 18 and want to see adult content?
![A complete backup of https://breastfeedingusa.org](https://www.archivebay.com/archive6/images/2a2e9bb1-553d-438f-9db0-fee5289d3c01.png)
A complete backup of https://breastfeedingusa.org
Are you over 18 and want to see adult content?
![A complete backup of https://menace-theoriste.fr](https://www.archivebay.com/archive6/images/bd991d7e-df79-4cc7-98fb-adeacf81b54b.png)
A complete backup of https://menace-theoriste.fr
Are you over 18 and want to see adult content?
![A complete backup of https://rouge-media.com](https://www.archivebay.com/archive6/images/b47a25c8-63b9-4c11-b88f-a2d9256955e5.png)
A complete backup of https://rouge-media.com
Are you over 18 and want to see adult content?
Text
and new
style string formatting API with practical examples. All examples on this page work out of the box with with Python 2.7, 3.2, 3.3, 3.4, and 3.5 without requiring any additional libraries. Further details about these two formatting methods can be found in the official Python documentation:* old style
* new style
If you want to contribute more examples, feel free to create a pull-request on Github !TABLE OF CONTENTS:
* Basic formatting
* Value conversion
* Padding and aligning strings * Truncating long strings * Combining truncating and padding* Numbers
* Padding numbers
* Signed numbers
* Named placeholders * Getitem and Getattr* Datetime
* Parametrized formats* Custom objects
BASIC FORMATTING
Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate. Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.OLD
'%s %s' % ('one', 'two')NEW
'{} {}'.format('one', 'two')OUTPUT
_o__n__e__ __t__w__o_OLD
'%d %d' % (1, 2)NEW
'{} {}'.format(1, 2)OUTPUT
_1__ __2_
With new style formatting it is possible (and in Python 2.6 even mandatory) to give placeholders an explicit positional index. This allows for re-arranging the order of display without changing thearguments.
This operation is not available with old-style formatting.NEW
'{1} {0}'.format('one', 'two')OUTPUT
_t__w__o__ __o__n__e_VALUE CONVERSION
The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !rconversion flags.
In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.SETUP
class Data(object):def __str__(self):
return 'str'
def __repr__(self):return 'repr'
OLD
'%s %r' % (Data(), Data())NEW
'{0!s} {0!r}'.format(Data())OUTPUT
_s__t__r__ __r__e__p__r_ In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...) instead.SETUP
class Data(object): def __repr__(self):return 'räpr'
OLD
'%r %a' % (Data(), Data())NEW
'{0!r} {0!a}'.format(Data())OUTPUT
_r__ä__p__r__ __r__\__x__e__4__p__r_ PADDING AND ALIGNING STRINGS By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length. Unfortunately the default alignment differs between old and new style formatting. The old style defaults to right aligned while for newstyle it's left.
Align right:
OLD
'%10s' % ('test',)NEW
'{:>10}'.format('test')OUTPUT
_ __ __ __ __ __ __t__e__s__t_Align left:
OLD
'%-10s' % ('test',)NEW
'{:10}'.format('test')OUTPUT
_t__e__s__t__ __ __ __ __ __ _ Again, new style formatting surpasses the old variant by providing more control over how values are padded and aligned. You are able to choose the padding character: This operation is not available with old-style formatting.NEW
'{:_<10}'.format('test')OUTPUT
_t__e__s__t___________________ And also center align values: This operation is not available with old-style formatting.NEW
'{:^10}'.format('test')OUTPUT
_ __ __ __t__e__s__t__ __ __ _ When using center alignment where the length of the string leads to an uneven split of the padding characters the extra character will be placed on the right side: This operation is not available with old-style formatting.NEW
'{:^6}'.format('zip')OUTPUT
_ __z__i__p__ __ _ TRUNCATING LONG STRINGS Inverse to padding it is also possible to truncate overly long values to a specific number of characters. The number behind a . in the format specifies the precision of the output. For strings that means that the output is truncated to the specified length. In our example this would be 5 characters.OLD
'%.5s' % ('xylophone',)NEW
'{:.5}'.format('xylophone')OUTPUT
_x__y__l__o__p_
COMBINING TRUNCATING AND PADDING It is also possible to combine truncating and padding:OLD
'%-10.5s' % ('xylophone',)NEW
'{:10.5}'.format('xylophone')OUTPUT
_x__y__l__o__p__ __ __ __ __ _NUMBERS
Of course it is also possible to format numbers.Integers:
OLD
'%d' % (42,)
NEW
'{:d}'.format(42)
OUTPUT
_4__2_
Floats:
OLD
'%f' % (3.141592653589793,)NEW
'{:f}'.format(3.141592653589793)OUTPUT
_3__.__1__4__1__5__9__3_PADDING NUMBERS
Similar to strings numbers can also be constrained to a specificwidth.
OLD
'%4d' % (42,)
NEW
'{:4d}'.format(42)
OUTPUT
_ __ __4__2_
Again similar to truncating strings the precision for floating point numbers limits the number of positions after the decimal point. For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.OLD
'%06.2f' % (3.141592653589793,)NEW
'{:06.2f}'.format(3.141592653589793)OUTPUT
_0__0__3__.__1__4_
For integer values providing a precision doesn't make much sense and is actually forbidden in the new style (it will result in aValueError).
OLD
'%04d' % (42,)
NEW
'{:04d}'.format(42)
OUTPUT
_0__0__4__2_
SIGNED NUMBERS
By default only negative numbers are prefixed with a sign. This can bechanged of course.
OLD
'%+d' % (42,)
NEW
'{:+d}'.format(42)
OUTPUT
_+__4__2_
Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used forpositive ones.
OLD
'% d' % ((- 23),)NEW
'{: d}'.format((- 23))OUTPUT
_-__2__3_
OLD
'% d' % (42,)
NEW
'{: d}'.format(42)
OUTPUT
_ __4__2_
New style formatting is also able to control the position of the sign symbol relative to the padding. This operation is not available with old-style formatting.NEW
'{:=5d}'.format((- 23))OUTPUT
_-__ __ __2__3_
NEW
'{:=+5d}'.format(23)OUTPUT
_+__ __ __2__3_
NAMED PLACEHOLDERS
Both formatting styles support named placeholders.SETUP
data = {'first': 'Hodor', 'last': 'Hodor!'}OLD
'%(first)s %(last)s' % dataNEW
'{first} {last}'.format(**data)OUTPUT
_H__o__d__o__r__ __H__o__d__o__r__!_ .format() also accepts keyword arguments. This operation is not available with old-style formatting.NEW
'{first} {last}'.format(first='Hodor', last='Hodor!')OUTPUT
_H__o__d__o__r__ __H__o__d__o__r__!_GETITEM AND GETATTR
New style formatting allows even greater flexibility in accessing nested data structures. It supports accessing containers that support __getitem__ like for example dictionaries and lists: This operation is not available with old-style formatting.SETUP
person = {'first': 'Jean-Luc', 'last': 'Picard'}NEW
'{p} {p}'.format(p=person)OUTPUT
_J__e__a__n__-__L__u__c__ __P__i__c__a__r__d_SETUP
data =
NEW
'{d} {d}'.format(d=data)OUTPUT
_2__3__ __4__2_
As well as accessing attributes on objects via getattr(): This operation is not available with old-style formatting.SETUP
class Plant(object):type = 'tree'
NEW
'{p.type}'.format(p=Plant())OUTPUT
_t__r__e__e_
Both type of access can be freely mixed and arbitrarily nested: This operation is not available with old-style formatting.SETUP
class Plant(object):type = 'tree'
kinds =
NEW
'{p.type}: {p.kinds}'.format(p=Plant())OUTPUT
_t__r__e__e__:__ __o__a__k_DATETIME
New style formatting also allows objects to control their own rendering. This for example allows datetime objects to be formattedinline:
This operation is not available with old-style formatting.SETUP
from datetime import datetimeNEW
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))OUTPUT
_2__0__0__1__-__0__2__-__0__3__ __0__4__:__0__5_ PARAMETRIZED FORMATS Additionally, new style formatting allows all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon. Old style formatting also supports some parametrization but is much more limited. Namely it only allows parametrization of the width and precision of the output. Parametrized alignment and width: This operation is not available with old-style formatting.NEW
'{:{align}{width}}'.format('test', align='^', width='10')OUTPUT
_ __ __ __t__e__s__t__ __ __ _ Parametrized precision:OLD
'%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)NEW
'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)OUTPUT
_G__i__b__ __=__ __2__.__7__1__8_ Width and precision:OLD
'%*.*f' % (5, 2, 2.7182)NEW
'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)OUTPUT
_ __2__.__7__2_
The nested format can be used to replace _any_ part of the format spec, so the precision example above could be rewritten as: This operation is not available with old-style formatting.NEW
'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')OUTPUT
_G__i__b__ __=__ __2__.__7__2_ The components of a date-time can be set separately: This operation is not available with old-style formatting.SETUP
from datetime import datetime dt = datetime(2001, 2, 3, 4, 5)NEW
'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')OUTPUT
_2__0__0__1__-__0__2__-__0__3__ __0__4__:__0__5_ The nested formats can be positional arguments. Position depends on the order of the opening curly braces: This operation is not available with old-style formatting.NEW
'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)OUTPUT
_ __ __ __ __ __+__2__.__7__2_ And of course keyword arguments can be added to the mix as before: This operation is not available with old-style formatting.NEW
'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')OUTPUT
_ __ __ __ __ __+__2__.__7__2_CUSTOM OBJECTS
The datetime example works through the use of the __format__() magic method. You can define custom format handling in your own objects by overriding this method. This gives you complete control over theformat syntax used.
This operation is not available with old-style formatting.SETUP
class HAL9000(object): def __format__(self, format): if (format == 'open-the-pod-bay-doors'): return "I'm afraid I can't do that."return 'HAL 9000'
NEW
'{:open-the-pod-bay-doors}'.format(HAL9000())OUTPUT
_I__'__m__ __a__f__r__a__i__d__ __I__ __c__a__n__'__t__ __d__o__ __t__h__a__t__._ You might also like Python strftime referenceby Will McCutchen .
Curated by Ulrich Petri & Horst Gutmann Version: a1c121275553bb110befddb63ec540f9339acbf9 (built at 2017-04-30 18:51:04.145458+00:00)Details
Copyright © 2024 ArchiveBay.com. All rights reserved. Terms of Use | Privacy Policy | DMCA | 2021 | Feedback | Advertising | RSS 2.0