id
int64
0
25.6k
text
stringlengths
0
4.59k
700
programsand so on to illustratepython' struct module can both create and unpack packed binary data--raw bytes that record values that are not python objects--to be written to file in binary mode we'll study this technique in detail later in the bookbut the concept is simplethe following creates binary file in python (binary files work the same in xbut the "bstring literal prefix isn' required and won' be displayed)import struct packed struct pack('> sh' 'spam' packed '\ \ \ \ spam\ \ file open('data bin''wb'file write(packed file close(create packed binary data bytesnot objects or text open binary output file write packed binary data reading binary data back is essentially symmetricnot all programs need to tread so deeply into the low-level realm of bytesbut binary files make this easy in pythondata open('data bin''rb'read(data '\ \ \ \ spam\ \ data[ : 'spamlist(data[ struct unpack('> sh'data( 'spam' open/read binary data file bytesunaltered slice bytes in the middle sequence of -bit bytes unpack into objects again unicode text files text files are used to process all sorts of text-based datafrom memos to email content to json and xml documents in today' broader interconnected worldthoughwe can' really talk about text without also asking "what kind?"--you must also know the text' unicode encoding type if either it differs from your platform' defaultor you can' rely on that default for data portability reasons luckilythis is easier than it may sound to access files containing non-ascii unicode text of the sort introduced earlier in this we simply pass in an encoding name if the text in the file doesn' match the default encoding for our platform in this modepython text files automatically encode on writes and decode on reads per the encoding scheme name you provide in python xs 'sp\xc ms 'spams[ 'afile open('unidata txt'' 'encoding='utf- ' introducing python object types non-ascii unicode text sequence of characters write/encode utf- text
701
file close( characters written text open('unidata txt'encoding='utf- 'read(text 'spamlen(text read/decode utf- text chars (code pointsthis automatic encoding and decoding is what you normally want because files handle this on transfersyou may process text in memory as simple string of characters without concern for its unicode-encoded origins if neededthoughyou can also see what' truly stored in your file by stepping into binary moderead raw encoded bytes raw open('unidata txt''rb'read(raw 'sp\xc \ mlen(raw really bytes in utf- you can also encode and decode manually if you get unicode data from source other than file--parsed from an email message or fetched over network connectionfor exampletext encode('utf- ' 'sp\xc \ mraw decode('utf- ''spammanual encode to bytes manual decode to str this is also useful to see how text files would automatically encode the same string differently under different encoding namesand provides way to translate data to different encodings--it' different bytes in filesbut decodes to the same string in memory if you provide the proper encoding nametext encode('latin- ' 'sp\xc mtext encode('utf- ' '\xff\xfes\ \ \xc \ \ bytes differ in others len(text encode('latin- '))len(text encode('utf- ')( '\xff\xfes\ \ \xc \ \ decode('utf- ''spambut same string decoded this all works more or less the same in python xbut unicode strings are coded and display with leading " ,byte strings don' require or show leading " ,and unicode text files must be opened with codecs openwhich accepts an encoding name just like ' openand uses the special unicode string to represent content in memory binary file mode may seem optional in since normal files are just byte-based databut it' required to avoid changing line ends if present (more on this later in the book)files
702
codecs open('unidata txt'encoding='utf 'read( 'sp\xc mopen('unidata txt''rb'read('sp\xc \ mopen('unidata txt'read('sp\xc \ xread/decode text xread raw bytes xraw/undecoded too although you won' generally need to care about this distinction if you deal only with ascii textpython' strings and files are an asset if you deal with either binary data (which includes most types of mediaor text in internationalized character sets (which includes most content on the web and internet at large todaypython also supports non-ascii file names (not just content)but it' largely automatictools such as walkers and listers offer more control when neededthough we'll defer further details until other file-like tools the open function is the workhorse for most file processing you will do in python for more advanced tasksthoughpython comes with additional file-like toolspipesfifossocketskeyed-access filespersistent object shelvesdescriptor-based filesrelational and object-oriented database interfacesand more descriptor filesfor instancesupport file locking and other low-level toolsand sockets provide an interface for networking and interprocess communication we won' cover many of these topics in this bookbut you'll find them useful once you start programming python in earnest other core types beyond the core types we've seen so farthere are others that may or may not qualify for membership in the categorydepending on how broadly it is defined setsfor exampleare recent addition to the language that are neither mappings nor sequencesratherthey are unordered collections of unique and immutable objects you create sets by calling the built-in set function or using new set literals and expressions in and and they support the usual mathematical set operations (the choice of new syntax for set literals makes sensesince sets are much like the keys of valueless dictionary) set('spam' {' '' '' 'make set out of sequence in and make set with set literals in and xy tuple of two sets without parentheses ({' '' '' '' '}{' '' '' '} {' '' ' {' '' '' '' '' ' introducing python object types intersection union difference
703
{' '' ' false { * for in [ ]{ superset set comprehensions in and even less mathematically inclined programmers often find sets useful for common tasks such as filtering out duplicatesisolating differencesand performing order-neutral equality tests without sorting--in listsstringsand all other iterable objectslist(set([ ])[ set('spam'set('ham'{' '' 'set('spam'=set('asmp'true filtering out duplicates (possibly reorderedfinding differences in collections order-neutral equality tests (=is falsesets also support in membership teststhough all other collection types in python do too'pin set('spam')'pin 'spam''hamin ['eggs''spam''ham'(truetruetruein additionpython recently grew few new numeric typesdecimal numberswhich are fixed-precision floating-point numbersand fraction numberswhich are rational numbers with both numerator and denominator both can be used to work around the limitations and inherent inaccuracies of floating-point math ( / ( / floating-point (add in python ximport decimal decimal decimal(' ' decimal(' 'decimalsfixed precision decimal getcontext(prec decimal decimal(' 'decimal decimal(' 'decimal(' 'from fractions import fraction fraction( fraction( fraction( fraction( fractionsnumerator+denominator python also comes with booleans (with predefined true and false objects that are essentially just the integers and with custom display logic)and it has long supported special placeholder object called none commonly used to initialize names and objectsother core types
704
(falsetruebool('spam'true booleans object' boolean value none none placeholder print(xnone [none initialize list of nones [nonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonea list of nones how to break your code' flexibility 'll have more to say about all of python' object types laterbut one merits special treatment here the type objectreturned by the type built-in functionis an object that gives the type of another objectits result differs slightly in xbecause types have merged with classes completely (something we'll explore in the context of "new-styleclasses in part viassuming is still the list of the prior sectionin python xtype(ltype(type( )in python xtype(ltype(type( )typestype of is list type object even types are objects xtypes are classesand vice versa see for more on class types besides allowing you to explore your objects interactivelythe type object in its most practical application allows code to check the types of the objects it processes in factthere are at least three ways to do so in python scriptif type( =type([])print('yes'type testingif you must yes if type( =listprint('yes'using the type name yes if isinstance(llist)print('yes'object-oriented tests yes now that 've shown you all these ways to do type testinghoweveri am required by law to tell you that doing so is almost always the wrong thing to do in python program (and often sign of an ex- programmer first starting to use python!the reason why introducing python object types
705
code units such as functionsbut it' (perhaps thecore python concept by checking for specific types in your codeyou effectively break its flexibility--you limit it to working on just one type without such testsyour code may be able to work on whole range of types this is related to the idea of polymorphism mentioned earlierand it stems from python' lack of type declarations as you'll learnin pythonwe code to object interfaces (operations supported)not to types that iswe care what an object doesnot what it is not caring about specific types means that code is automatically applicable to many of them--any object with compatible interface will workregardless of its specific type although type checking is supported--and even required in some rare cases--you'll see that it' not usually the "pythonicway of thinking in factyou'll find that polymorphism is probably the key idea behind using python well user-defined classes we'll study object-oriented programming in python--an optional but powerful feature of the language that cuts development time by supporting programming by customization--in depth later in this book in abstract termsthoughclasses define new types of objects that extend the core setso they merit passing glance here sayfor examplethat you wish to have type of object that models employees although there is no such specific core type in pythonthe following user-defined class might fit the billclass workerdef __init__(selfnamepay)self name name self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay *( percentinitialize when created self is the new object split string on blanks update pay in place this class defines new kind of object that will have name and pay attributes (sometimes called state information)as well as two bits of behavior coded as functions (normally called methodscalling the class like function generates instances of our new typeand the class' methods automatically receive the instance being processed by given method call (in the self argument)bob worker('bob smith' sue worker('sue jones' bob lastname('smithsue lastname('jonessue giveraise sue pay make two instances each has name and pay attrs call methodbob is self sue is the self subject updates sue' pay other core types
706
an implied subject in functions within class in sensethoughthe class-based type simply builds on and uses core types-- user-defined worker object herefor exampleis just collection of string and number (name and payrespectively)plus functions for processing those two built-in objects the larger story of classes is that their inheritance mechanism supports software hierarchies that lend themselves to customization by extension we extend software by writing new classesnot by changing what already works you should also know that classes are an optional feature of pythonand simpler built-in types such as lists and dictionaries are often better tools than user-coded classes this is all well beyond the bounds of our introductory object-type tutorialthoughso consider this just previewfor full disclosure on user-defined types coded with classesyou'll have to read on because classes build upon other tools in pythonthey are one of the major goals of this book' journey and everything else as mentioned earliereverything you can process in python script is type of objectso our object type tour is necessarily incomplete howevereven though everything in python is an "object,only those types of objects we've met so far are considered part of python' core type set other types in python either are objects related to program execution (like functionsmodulesclassesand compiled code)which we will study lateror are implemented by imported module functionsnot language syntax the latter of these also tend to have application-specific roles--text patternsdatabase interfacesnetwork connectionsand so on moreoverkeep in mind that the objects we've met here are objectsbut not necessarily object-oriented-- concept that usually requires inheritance and the python class statementwhich we'll meet again later in this book stillpython' core objects are the workhorses of almost every python script you're likely to meetand they usually are the basis of larger noncore types summary and that' wrap for our initial data type tour this has offered brief introduction to python' core object types and the sorts of operations we can apply to them we've studied generic operations that work on many object types (sequence operations such as indexing and slicingfor example)as well as type-specific operations available as method calls (for instancestring splits and list appendswe've also defined some key termssuch as immutabilitysequencesand polymorphism along the waywe've seen that python' core object types are more flexible and powerful than what is available in lower-level languages such as for instancepython' lists and dictionaries obviate most of the work you do to support collections and introducing python object types
707
dictionaries are collections of other objects that are indexed by key instead of by position both dictionaries and lists may be nestedcan grow and shrink on demandand may contain objects of any type moreovertheir space is automatically cleaned up as you go we've also seen that strings and files work hand in hand to support rich variety of binary and text data 've skipped most of the details here in order to provide quick tourso you shouldn' expect all of this to have made sense yet in the next few we'll start to dig deepertaking second pass over python' core object types that will fill in details omitted hereand give you deeper understanding we'll start off the next with an in-depth look at python numbers firstthoughhere is another quiz to review test your knowledgequiz we'll explore the concepts introduced in this in more detail in upcoming so we'll just cover the big ideas here name four of python' core data types why are they called "coredata types what does "immutablemeanand which three of python' core types are considered immutable what does "sequencemeanand which three types fall into that category what does "mappingmeanand which core type is mapping what is "polymorphism,and why should you caretest your knowledgeanswers numbersstringslistsdictionariestuplesfilesand sets are generally considered to be the core object (datatypes typesnoneand booleans are sometimes classified this way as well there are multiple number types (integerfloating pointcomplexfractionand decimaland multiple string types (simple strings and unicode strings in python xand text strings and byte strings in python they are known as "coretypes because they are part of the python language itself and are always availableto create other objectsyou generally must call functions in imported modules most of the core types have specific syntax for generating the objects'spam'for exampleis an expression that makes string and determines the set of operations that can be applied to it because of thiscore types are hardwired into python' syntax in contrastyou must call the built-in open function to create file object (even though this is usually considered core type too an "immutableobject is an object that cannot be changed after it is created numbersstringsand tuples in python fall into this category while you cannot test your knowledgeanswers
708
an expression bytearrays in recent pythons offer mutability for textbut they are not normal stringsand only apply directly to text if it' simple -bit kind ( ascii "sequenceis positionally ordered collection of objects stringslistsand tuples are all sequences in python they share common sequence operationssuch as indexingconcatenationand slicingbut also have type-specific method calls related term"iterable,means either physical sequenceor virtual one that produces its items on request the term "mappingdenotes an object that maps keys to associated values python' dictionary is the only mapping type in the core type set mappings do not maintain any left-to-right positional orderingthey support access to data stored by keyplus type-specific method calls "polymorphismmeans that the meaning of an operation (like +depends on the objects being operated on this turns out to be key idea (perhaps the key ideabehind using python well--not constraining code to specific types makes that code automatically applicable to many types introducing python object types
709
numeric types this begins our in-depth tour of the python language in pythondata takes the form of objects--either built-in objects that python providesor objects we create using python tools and other languages such as in factobjects are the basis of every python program you will ever write because they are the most fundamental notion in python programmingobjects are also our first focus in this book in the preceding we took quick pass over python' core object types although essential terms were introduced in that we avoided covering too many specifics in the interest of space herewe'll begin more careful second look at data type conceptsto fill in details we glossed over earlier let' get started by exploring our first data type categorypython' numeric types and operations numeric type basics most of python' number types are fairly typical and will probably seem familiar if you've used almost any other programming language in the past they can be used to keep track of your bank balancethe distance to marsthe number of visitors to your websiteand just about any other numeric quantity in pythonnumbers are not really single object typebut category of similar types python supports the usual numeric types (integers and floating points)as well as literals for creating numbers and expressions for processing them in additionpython provides more advanced numeric programming support and objects for more advanced work complete inventory of python' numeric toolbox includesinteger and floating-point objects complex number objects decimalfixed-precision objects fractionrational number objects setscollections with numeric operations
710
built-in functions and modulesroundmathrandometc expressionsunlimited integer precisionbitwise operationshexoctaland binary formats third-party extensionsvectorslibrariesvisualizationplottingetc because the types in this list' first bullet item tend to see the most action in python codethis starts with basic numbers and fundamentalsthen moves on to explore the other types on this listwhich serve specialized roles we'll also study sets herewhich have both numeric and collection qualitiesbut are generally considered more the former than the latter before we jump into codethoughthe next few sections get us started with brief overview of how we write and process numbers in our scripts numeric literals among its basic typespython provides integerswhich are positive and negative whole numbersand floating-point numberswhich are numbers with fractional part (sometimes called "floatsfor verbal economypython also allows us to write integers using hexadecimaloctaland binary literalsoffers complex number typeand allows integers to have unlimited precision--they can grow to have as many digits as your memory space allows table - shows what python' numeric types look like when written out in program as literals or constructor function calls table - numeric literals and constructors literal interpretation - integers (unlimited size - + floating-point numbers ff octalhexand binary literals in ff octaloctalhexand binary literals in + + complex number literals set('spam'){ sets and construction forms decimal(' ')fraction( decimal and fraction extension types bool( )truefalse boolean type and constants in generalpython' numeric type literals are straightforward to writebut few coding concepts are worth highlighting hereinteger and floating-point literals integers are written as strings of decimal digits floating-point numbers have decimal point and/or an optional signed exponent introduced by an or and followed by an optional sign if you write number with decimal point or exponentpython makes it floating-point object and uses floating-point (not integer numeric types
711
as the compiler used to build the python interpreter gives to doubles integers in python xnormal and long in python there are two integer typesnormal (often bitsand long (unlimited precision)and an integer may end in an or to force it to become long integer because integers are automatically converted to long integers when their values overflow their allocated bitsyou never need to type the letter yourself-python automatically converts up to long integer when extra precision is needed integers in python xa single type in python xthe normal and long integer types have been merged--there is only integerwhich automatically supports the unlimited precision of python ' separate long integer type because of thisintegers can no longer be coded with trailing or land integers never print with this character either apart from thismost programs are unaffected by this changeunless they do type testing that checks for long integers hexadecimaloctaland binary literals integers may be coded in decimal (base )hexadecimal (base )octal (base )or binary (base )the last three of which are common in some programming domains hexadecimals start with leading or xfollowed by string of hexadecimal digits ( - and -fhex digits may be coded in loweror uppercase octal literals start with leading or (zero and loweror uppercase letter )followed by string of digits ( - in xoctal literals can also be coded with just leading but not in --this original octal form is too easily confused with decimaland is replaced by the new formatwhich can also be used in as of binary literalsnew as of and begin with leading or bfollowed by binary digits ( - note that all of these literals produce integer objects in program codethey are just alternative syntaxes for specifying values the built-in calls hex( )oct( )and bin(iconvert an integer to its representation string in these three basesand int(strbaseconverts runtime string to an integer per given base complex numbers python complex literals are written as realpart+imaginarypartwhere the imagi narypart is terminated with or the realpart is technically optionalso the imaginarypart may appear on its own internallycomplex numbers are implemented as pairs of floating-point numbersbut all numeric operations perform complex math when applied to complex numbers complex numbers may also be created with the complex(realimagbuilt-in call coding other numeric types as we'll see later in this there are additional numeric types at the end of table - that serve more advanced or specialized roles you create some of these numeric type basics
712
have literal syntax all their own ( setsbuilt-in numeric tools besides the built-in number literals and construction calls shown in table - python provides set of tools for processing number objectsexpression operators +-*/>>**&etc built-in mathematical functions powabsroundinthexbinetc utility modules randommathetc we'll meet all of these as we go along although numbers are primarily processed with expressionsbuilt-insand modulesthey also have handful of type-specific methods todaywhich we'll meet in this as well floating-point numbersfor examplehave an as_integer_ratio method that is useful for the fraction number typeand an is_integer method to test if the number is an integer integers have various attributesincluding new bit_length method introduced in python that gives the number of bits necessary to represent the object' value moreoveras part collection and part numbersets also support both methods and expressions since expressions are the most essential tool for most number typesthoughlet' turn to them next python expression operators perhaps the most fundamental tool that processes numbers is the expressiona combination of numbers (or other objectsand operators that computes value when executed by python in pythonyou write expressions using the usual mathematical notation and operator symbols for instanceto add two numbers and you would say ywhich tells python to apply the operator to the values named by and the result of the expression is the sum of and yanother number object table - lists all the operator expressions available in python many are self-explanatoryfor instancethe usual mathematical operators (+-*/and so onare supported few will be familiar if you've used other languages in the pastcomputes division remainder<performs bitwise left-shiftcomputes bitwise and resultand so on others are more python-specificand not all are numeric in naturefor examplethe is operator tests object identity ( address in memorya strict form of equality)and lambda creates unnamed functions numeric types
713
operators description yield generator function send protocol lambda argsexpression anonymous function generation if else ternary selection ( is evaluated only if is truex or logical or ( is evaluated only if is falsex and logical and ( is evaluated only if is truenot logical negation in yx not in membership (iterablessetsx is yx is not object identity tests yx > magnitude comparisonset subset and supersetx =yx ! value equality operators bitwise orset union bitwise xorset symmetric difference bitwise andset intersection shift left or right by bits additionconcatenationx subtractionset difference multiplicationrepetitionx remainderformatx yx / divisiontrue and floor - + negationidentity ~ bitwise not (inversionx * power (exponentiationx[iindexing (sequencemappingothersx[ : :kslicing xcall (functionmethodclassother callablex attr attribute reference tupleexpressiongenerator expression listlist comprehension dictionarysetset and dictionary comprehensions since this book addresses both python and xhere are some notes about version differences and recent additions related to the operators in table - numeric type basics
714
xthe latter of these options is removed because it is redundant in either versionbest practice is to use ! for all value inequality tests in python xa backquotes expression `xworks the same as repr(xand converts objects to display strings due to its obscuritythis expression is removed in python xuse the more readable str and repr built-in functionsdescribed in "numeric display formats the / floor division expression always truncates fractional remainders in both python and the expression performs true division in (retaining remaindersand classic division in (truncating for integerssee "divisionclassicfloorand trueon page the syntax is used for both list literals and list comprehension expressions the latter of these performs an implied loop and collects expression results in new list see and for examples the syntax is used for tuples and expression groupingas well as generator expressions-- form of list comprehension that produces results on demandinstead of building result list see and for examples the parentheses may sometimes be omitted in all three contexts the syntax is used for dictionary literalsand in python and for set literals and both dictionary and set comprehensions see the set coverage in this as well as and for examples the yield and ternary if/else selection expressions are available in python and later the former returns sendarguments in generatorsthe latter is shorthand for multiline if statement yield requires parentheses if not alone on the right side of an assignment statement comparison operators may be chainedx produces the same result as and see "comparisonsnormal and chainedon page for details in recent pythonsthe slice expression [ : :kis equivalent to indexing with slice objectx[slice(ijk)in python xmagnitude comparisons of mixed types are allowedand convert numbers to common typeand order other mixed types according to type names in python xnonnumeric mixed-type magnitude comparisons are not allowed and raise exceptionsthis includes sorts by proxy magnitude comparisons for dictionaries are also no longer supported in python (though equality tests are)comparing sorted(adict items()is one possible replacement we'll see most of the operators in table - in action laterfirstthoughwe need to take quick look at the ways these operators may be combined in expressions numeric types
715
as in most languagesin pythonyou code more complex expressions by stringing together the operator expressions in table - for instancethe sum of two multiplications might be written as mix of variables and operatorsa sohow does python know which operation to perform firstthe answer to this question lies in operator precedence when you write an expression with more than one operatorpython groups its parts according to what are called precedence rulesand this grouping determines the order in which the expression' parts are computed table - is ordered by operator precedenceoperators lower in the table have higher precedenceand so bind more tightly in mixed expressions operators in the same row in table - generally group from left to right when combined (except for exponentiationwhich groups right to leftand comparisonswhich chain left to rightfor exampleif you write zpython evaluates the multiplication first ( )then adds that result to because has higher precedence (is lower in the tablethan similarlyin this section' original exampleboth multiplications ( and dwill happen before their results are added parentheses group subexpressions you can forget about precedence completely if you're careful to group parts of expressions with parentheses when you enclose subexpressions in parenthesesyou override python' precedence rulespython always evaluates expressions in parentheses first before using their results in the enclosing expressions for instanceinstead of coding zyou could write one of the following to force python to evaluate the expression in the desired order( yz ( zin the first caseis applied to and firstbecause this subexpression is wrapped in parentheses in the second casethe is performed first (just as if there were no parentheses at allgenerally speakingadding parentheses in large expressions is good idea--it not only forces the evaluation order you wantbut also aids readability mixed types are converted up besides mixing operators in expressionsyou can also mix numeric types for instanceyou can add an integer to floating-point number numeric type basics
716
the answer is simpleespecially if you've used almost any other language beforein mixed-type numeric expressionspython first converts operands up to the type of the most complicated operandand then performs the math on same-type operands this behavior is similar to type conversions in the language python ranks the complexity of numeric types like sointegers are simpler than floatingpoint numberswhich are simpler than complex numbers sowhen an integer is mixed with floating pointas in the preceding examplethe integer is converted up to floating-point value firstand floating-point math yields the floating-point result integer to floatfloat math/result similarlyany mixed-type expression where one operand is complex number results in the other operand being converted up to complex numberand the expression yields complex result in python xnormal integers are also converted to long integers whenever their values are too large to fit in normal integerin xintegers subsume longs entirely you can force the issue by calling built-in functions to convert types manuallyint( float( truncates float to integer converts integer to float howeveryou won' usually need to do thisbecause python automatically converts up to the more complex type within an expressionthe results are normally what you want alsokeep in mind that all these mixed-type conversions apply only when mixing numeric types ( an integer and floating pointin an expressionincluding those using numeric and comparison operators in generalpython does not convert across any other type boundaries automatically adding string to an integerfor exampleresults in an errorunless you manually convert one or the otherwatch for an example when we meet strings in in python xnonnumeric mixed types can be comparedbut no conversions are performed--mixed types compare according to rule that seems deterministic but not aesthetically pleasingit compares the string names of the objectstypes in xnonnumeric mixed-type magnitude comparisons are never allowed and raise exceptions note that this applies to comparison operators such as onlyother operators like do not allow mixed nonnumeric types in either or numeric types
717
although we're focusing on built-in numbers right nowall python operators may be overloaded ( implementedby python classes and extension types to work on objects you create for instanceyou'll see later that objects coded with classes may be added or concatenated with + expressionsindexed with [iexpressionsand so on furthermorepython itself automatically overloads some operatorssuch that they perform different actions depending on the type of built-in objects being processed for examplethe operator performs addition when applied to numbers but performs concatenation when applied to sequence objects such as strings and lists in factcan mean anything at all when applied to objects you define with classes as we saw in the prior this property is usually called polymorphism-- term indicating that the meaning of an operation depends on the type of the objects being operated on we'll revisit this concept when we explore functions in because it becomes much more obvious feature in that context numbers in action on to the codeprobably the best way to understand numeric objects and expressions is to see them in actionso with those basics in hand let' start up the interactive command line and try some simple but illustrative operations (be sure to see for pointers if you need help starting an interactive sessionvariables and basic expressions first of alllet' exercise some basic math in the following interactionwe first assign two variables ( and bto integers so we can use them later in larger expression variables are simply names--created by you or python--that are used to keep track of information in your program we'll say more about this in the next but in pythonvariables are created when they are first assigned values variables are replaced with their values when used in expressions variables must be assigned before they can be used in expressions variables refer to objects and are never declared ahead of time in other wordsthese assignments cause the variables and to spring into existence automaticallypython name creatednot declared ahead of time 've also used comment here recall that in python codetext after mark and continuing to the end of the line is considered to be comment and is ignored by numbers in action
718
and an important part of programming 've added them to most of this book' examples to help explain the code in the next part of the bookwe'll meet related but more functional feature--documentation strings--that attaches the text of your comments to objects so it' available after your code is loaded because code you type interactively is temporarythoughyou won' normally write comments in this context if you're working alongthis means you don' need to type any of the comment text from the through to the end of the lineit' not required part of the statements we're running this way nowlet' use our new integer objects in some expressions at this pointthe values of and are still and respectively variables like these are replaced with their values whenever they're used inside an expressionand the expression results are echoed back immediately when we're working interactivelya ( ( * ( * ( addition ( )subtraction ( multiplication ( )division ( modulus (remainder)power ( * mixed-type conversions technicallythe results being echoed back here are tuples of two values because the lines typed at the prompt contain two expressions separated by commasthat' why the results are displayed in parentheses (more on tuples laternote that the expressions work because the variables and within them have been assigned values if you use different variable that has not yet been assignedpython reports an error rather than filling in some default valuec traceback (most recent call last)file ""line in nameerrorname 'cis not defined you don' need to predeclare variables in pythonbut they must have been assigned at least once before you can use them in practicethis means you have to initialize counters to zero before you can add to theminitialize lists to an empty list before you can append to themand so on here are two slightly larger expressions to illustrate operator grouping and more about conversionsand preview difference in the division operator in python and xb ( same as (( [use in xsame as ( ( )[use print before in the first expressionthere are no parenthesesso python automatically groups the components according to its precedence rules--because is lower in table - than numeric types
719
been organized with parentheses as shown in the comment to the right of the code alsonotice that all the numbers are integers in the first expression because of thatpython ' performs integer division and addition and will give result of whereas python ' performs true divisionwhich always retains fractional remainders and gives the result shown if you want ' integer division in xcode this as / aif you want ' true division in xcode this as (more on division in momentin the second expressionparentheses are added around the part to force python to evaluate it first ( before the /we also made one of the operands floating point by adding decimal point because of the mixed typespython converts the integer referenced by to floating-point value ( before performing the if instead all the numbers in this expression were integersinteger division ( would yield the truncated integer in python but the floating point shown in python againstay tuned for formal division details numeric display formats if you're using python python or earlierthe result of the last of the preceding examples may look bit odd the first time you see itb ( pythons < echoes give more (or fewerdigits print( ( ) but print rounds off digits we met this phenomenon briefly in the prior and it' not present in pythons and later the full story behind this odd result has to do with the limitations of floating-point hardware and its inability to exactly represent some values in limited number of bits because computer architecture is well beyond this book' scopethoughwe'll finesse this by saying that your computer' floating-point hardware is doing the best it canand neither it nor python is in error here in factthis is really just display issue--the interactive prompt' automatic result echo shows more digits than the print statement here only because it uses different algorithm it' the same number in memory if you don' want to see all the digitsuse printas this sidebar "str and repr display formatson page will explainyou'll get user-friendly display as of and python' floating-point display logic tries to be more intelligentusually showing fewer decimal digitsbut occasionally more notehoweverthat not all values have so many digits to display numbers in action
720
using print and automatic echoes (the following are all run in python and may vary slightly in older versions)num num print(num auto-echoes print explicitly '%enum ' - '% fnum ' '{ : }format(num' string formatting expression alternative floating-point format string formatting methodpython and later the last three of these expressions employ string formattinga tool that allows for format flexibilitywhich we will explore in the upcoming on strings (its results are strings that are typically printed to displays or reports str and repr display formats technicallythe difference between default interactive echoes and print corresponds to the difference between the built-in repr and str functionsrepr('spam'"'spam'str('spam''spamused by echoesas-code form used by printuser-friendly form both of these convert arbitrary objects to their string representationsrepr (and the default interactive echoproduces results that look as though they were codestr (and the print operationconverts to typically more user-friendly format if available some objects have both-- str for general useand repr with extra details this notion will resurface when we study both strings and operator overloading in classesand you'll find more on these built-ins in general later in the book besides providing print strings for arbitrary objectsthe str built-in is also the name of the string data typeand in may be called with an encoding name to decode unicode string from byte string ( str( 'xy''utf '))and serves as an alternative to the bytes decode method we met in we'll study the latter advanced role in of this book comparisonsnormal and chained so farwe've been dealing with standard numeric operations (addition and multiplication)but numberslike all python objectscan also be compared normal comparisons work for numbers exactly as you' expect--they compare the relative magnitudes numeric types
721
action on in larger statement and program true > true = true ! false less than greater than or equalmixed-type converted to equal value not equal value notice again how mixed types are allowed in numeric expressions (only)in the second test herepython compares values in terms of the more complex typefloat interestinglypython also allows us to chain multiple comparisons together to perform range tests chained comparisons are sort of shorthand for larger boolean expressions in shortpython lets us string together magnitude comparison tests to code chained comparisons such as range tests the expression ( )for instancetests whether is between and cit is equivalent to the boolean test ( and cbut is easier on the eyes (and the keyboardfor exampleassume the following assignmentsx the following two expressions have identical effectsbut the first is shorter to typeand it may run slightly faster since python needs to evaluate only oncex true and true chained comparisonsrange tests the same equivalence holds for false resultsand arbitrary chain lengths are allowedx false false true false you can use other comparisons in chained testsbut the resulting expressions can become nonintuitive unless you evaluate them the way python does the followingfor instanceis false just because is not equal to = false same as = and not same asfalse (which means which is true!numbers in action
722
true and false are just customized and one last note here before we move onchaining asidenumeric comparisons are based on magnitudeswhich are generally simple--though floating-point numbers may not always work as you' expectand may require conversions or other massaging to be compared meaningfully = false int( =int( true shouldn' this be trueclose to but not exactlylimited precision ok if convertsee also roundfloortrunc ahead decimals and fractions (aheadmay help here too this stems from the fact that floating-point numbers cannot represent some values exactly due to their limited number of bits-- fundamental issue in numeric programming not unique to pythonwhich we'll learn more about later when we meet decimals and fractionstools that can address such limitations firstthoughlet' continue our tour of python' core numeric operationswith deeper look at division divisionclassicfloorand true you've seen how division works in the previous sectionsso you should know that it behaves slightly differently in python and in factthere are actually three flavors of divisionand two different division operatorsone of which changes in this story gets bit detailedbut it' another major change in and can break codeso let' get the division operator facts straightx classic and true division in python xthis operator performs classic divisiontruncating results for integersand keeping remainders ( fractional partsfor floating-point numbers in python xit performs true divisionalways keeping remainders in floating-point resultsregardless of types / floor division added in python and available in both python and xthis operator always truncates fractional remainders down to their floorregardless of types its result type depends on the types of its operands true division was added to address the fact that the results of the original classic division model are dependent on operand typesand so can be difficult to anticipate in dynamically typed language like python classic division was removed in because of this constraint--the and /operators implement true and floor division in python defaults to classic and floor divisionbut you can enable true division as an option in sum numeric types
723
any remainderregardless of operand types the /performs floor divisionwhich truncates the remainder and returns an integer for integer operands or float if any operand is float in xthe does classic divisionperforming truncating integer division if both operands are integers and float division (keeping remaindersotherwise the /does floor division and works as it does in xperforming truncating division for integers and floor division for floats here are the two operators at work in and --the first operation in each set is the crucial difference between the lines that may impact codec:\codec:\python \python differs in xkeeps remainder same in xkeeps remainder / same in xtruncates remainder / same in xtruncates to floor :\codec:\python \python this might break on porting to / use this in if truncation needed / notice that the data type of the result for /is still dependent on the operand types in xif either is floatthe result is floatotherwiseit is an integer although this may seem similar to the type-dependent behavior of in that motivated its change in xthe type of the return value is much less critical than differences in the return value itself moreoverbecause /was provided in part as compatibility tool for programs that rely on truncating integer division (and this is more common than you might expect)it must return integers for integers using /instead of in when integer truncation is required helps make code -compatible supporting either python although behavior differs in and xyou can still support both versions in your code if your programs depend on truncating integer divisionuse /in both and as just mentioned if your programs require floating-point results with remainders numbers in action
724
xx / always truncatesalways an int result for ints in and float(zguarantees float division with remainder in either or alternativelyyou can enable division in with __future__ importrather than forcing it with float conversionsc:\codec:\python \python from __future__ import division / enable "/behavior integer /is the same in both this special from statement applies to the rest of your session when typed interactively like thisand must appear as the first executable line when used in script file (and alaswe can import from the future in pythonbut not the pastinsert something about talking to "the dochere floor versus truncation one subtletythe /operator is informally called truncating divisionbut it' more accurate to refer to it as floor division--it truncates the result down to its floorwhich means the closest whole number below the true result the net effect is to round downnot strictly truncateand this matters for negatives you can see the difference for yourself with the python math module (modules must be imported before you can use their contentsmore on this later)import math math floor( math floor(- - math trunc( math trunc(- - closest number below value truncate fractional part (toward zerowhen running division operatorsyou only really truncate for positive resultssince truncation is the same as floorfor negativesit' floor result (reallythey are both floorbut floor is the same as truncation for positiveshere' the case for xc:\codec:\python \python - ( - / /- ( - - ( - numeric types truncates to floorrounds to first lower integer becomes - becomes -
725
( - ditto for floatsthough result is float too the case is similarbut results differ againc:codec:\python \python - ( - / /- ( - differs in this and the rest are the same in and - ( - / /- ( - if you really want truncation toward zero regardless of signyou can always run float division result through math truncregardless of python version (also see the round built-in for related functionalityand the int built-inwhich has the same effect here but requires no import) :\codec:\python \python import math - - /- - math trunc( - - :\codec:\python \python import math float(- - - /- (- - math trunc( float(- )- keep remainder floor below result truncate instead of floor (same as int()remainder in floor in truncate in why does truncation matteras wrap-upif you are using xhere is the short story on division operators for reference( )( )( - )( - ( - - true division ( / )( / )( /- )( /- ( - - floor division ( )( )( / )( / ( both numbers in action
726
for readersdivision works as follows (the three bold outputs of integer division differ from )( )( )( - )( - ( - - classic division (differs( / )( / )( /- )( /- ( - - floor division (same( )( )( / )( / ( both it' possible that the nontruncating behavior of in may break significant number of programs perhaps because of language legacymany programmers rely on division truncation for integers and will have to learn to use /in such contexts instead you should do so in all new and code you write today--in the former for compatibilityand in the latter because does not truncate in watch for simple prime number while loop example in and corresponding exercise at the end of part iv that illustrates the sort of code that may be impacted by this change also stay tuned for more on the special from command used in this sectionit' discussed further in integer precision division may differ slightly across python releasesbut it' still fairly standard here' something bit more exotic as mentioned earlierpython integers support unlimited size python has separate type for long integersbut it automatically converts any number too large to store in normal integer to this type henceyou don' need to code any special syntax to use longsand the only way you can tell that you're using longs is that they print with trailing " " unlimited-precision integers are convenient built-in tool for instanceyou can use them to count the national debt in pennies in python directly (if you are so inclinedand have enough memory on your computer for this year' budgetthey are also why we were able to raise to such large powers in the examples in here are the and cases * * numeric types
727
is usually substantially slower than normal when numbers grow large howeverif you need the precisionthe fact that it' built in for you to use will likely outweigh its performance penalty complex numbers although less commonly used than the types we've been exploring thus farcomplex numbers are distinct core object type in python they are typically used in engineering and science applications if you know what they areyou know why they are usefulif notconsider this section optional reading complex numbers are represented as two floating-point numbers--the real and imaginary parts--and you code them by adding or suffix to the imaginary part we can also write complex numbers with nonzero real part by adding the two parts with for examplethe complex number with real part of and an imaginary part of - is written - here are some examples of complex math at work (- + ( + ( ( + jcomplex numbers also allow us to extract their parts as attributessupport all the usual mathematical expressionsand may be processed with tools in the standard cmath module (the complex version of the standard math modulebecause complex numbers are rare in most programming domainsthoughwe'll skip the rest of this story here check python' language reference manual for additional details hexoctalbinaryliterals and conversions python integers can be coded in hexadecimaloctaland binary notationin addition to the normal base- decimal coding we've been using so far the first three of these may at first seem foreign to -fingered beingsbut some programmers find them convenient alternatives for specifying valuesespecially when their mapping to bytes and bits is important the coding rules were introduced briefly at the start of this let' look at some live examples here keep in mind that these literals are simply an alternative syntax for specifying the value of an integer object for examplethe following literals coded in python or produce normal integers with the specified values in all three bases in memoryan integer' value is the sameregardless of the base we use to specify it ( xff octal literalsbase digits - ( +hex literalsbase digits - / - ( xnumbers in action
728
( binary literalsbase digits - ( +herethe octal value the hex value xffand the binary value are all decimal the digits in the hex valuefor exampleeach mean in decimal and -bit in binaryand reflect powers of thusthe hex value xff and others convert to decimal values as follows xff( ( * )( ( * )how hex/binary map to decimal ( ( ( * )( ( * )( xf ( *( ** *( ** *( ** *( ** )( python prints integer values in decimal (base by default but provides built-in functions that allow you to convert integers to other basesdigit stringsin python-literal form--useful when programs or users expect to see values in given baseoct( )hex( )bin( (' '' '' 'numbers=>digit strings the oct function converts decimal to octalhex to hexadecimaland bin to binary to go the other waythe built-in int function converts string of digits to an integerand an optional second argument lets you specify the numeric base--useful for numbers read from files as strings instead of coded in scripts ( digits=>numbers in scripts and strings int(' ')int(' ' )int(' ' )int(' ' ( int(' ' )int(' ' ( literal forms supported too the eval functionwhich you'll meet later in this booktreats strings as though they were python code thereforeit has similar effectbut usually runs more slowly--it actually compiles and runs the string as piece of programand it assumes the string being run comes from trusted source-- clever user might be able to submit string that deletes files on your machineso be careful with this calleval(' ')eval(' ')eval(' ')eval(' '( finallyyou can also convert integers to base-specific strings with string formatting method calls and expressionswhich return just digitsnot python literal strings'{ : }{ : }{ : }format( ' numbers=>digits '% % % % ( ' ffffsimilarin all pythons numeric types
729
two notes before moving on firstper the start of this python users should remember that you can code octals with simply leading zerothe original octal format in python ( ( new octal format in (same as xold octal literals in all (error in xin xthe syntax in the second of these examples generates an error even though it' not an error in xbe careful not to begin string of digits with leading zero unless you really mean to code an octal value python will treat it as base which may not work as you' expect-- is always decimal in xnot decimal (despite what you may or may not think!thisalong with symmetry with the hex and binary formsis why the octal format was changed in --you must use in xand probably should in and both for clarity and forward-compatibility with secondlynote that these literals can produce arbitrarily long integers the followingfor instancecreates an integer with hex notation and then displays it first in decimal and then in octal and binary with converters (run in herein the decimal and octal displays have trailing to denote its separate long typeand octals display without the letter ) xffffffffffffffffffffffffffff oct( ' bin( ' and so on speaking of binary digitsthe next section shows tools for processing individual bits bitwise operations besides the normal numeric operations (additionsubtractionand so on)python supports most of the numeric expressions available in the language this includes operators that treat integers as strings of binary bitsand can come in handy if your python code must deal with things like network packetsserial portsor packed binary data produced by program we can' dwell on the fundamentals of boolean math here--againthose who must use it probably already know how it worksand others can often postpone the topic altogether--but the basics are straightforward for instancehere are some of python' bitwise expression operators at work performing bitwise shift and boolean operations on integersx < decimal is in bits shift left bits numbers in action
730
bitwise or (either bit= ) bitwise and (both bits= ) in the first expressiona binary (in base is shifted left two slots to create binary ( the last two operations perform binary or to combine bits ( and binary and to select common bits ( & such bitmasking operations allow us to encode and extract multiple flags and other values within single integer this is one area where the binary and hexadecimal number support in python as of and become especially useful--they allow us to code and inspect numbers by bitstringsx < bin( < ' bin( ' bin( ' binary literals shift left binary digits string bitwise oreither bitwise andboth this is also true for values that begin life as hex literalsor undergo base conversionsx xff hex literals bin( ' bitwise xoreither but not both bin( ' int(' ' digits=>numberstring to int per base hex( number=>digitshex digit string ' also in this departmentpython and introduced new integer bit_length methodwhich allows you to query the number of bits required to represent number' value in binary you can often achieve the same effect by subtracting from the length of the bin string using the len built-in function we met in (to account for the leading " ")though it may be less efficientx bin( ) bit_length()len(bin( ) (' ' bin( )( bit_length()len(bin( ) (' ' numeric types
731
need itbut bitwise operations are often not as important in high-level language such as python as they are in low-level language such as as rule of thumbif you find yourself wanting to flip bits in pythonyou should think about which language you're really coding as we'll see in upcoming python' listsdictionariesand the like provide richer--and usually better--ways to encode information than bit stringsespecially when your data' audience includes readers of the human variety other built-in numeric tools in addition to its core object typespython also provides both built-in functions and standard library modules for numeric processing the pow and abs built-in functionsfor instancecompute powers and absolute valuesrespectively here are some examples of the built-in math module (which contains most of the tools in the language' math libraryand few built-in functions at work in as described earliersome floating-point displays may show more or fewer digits in pythons before and import math math pimath ( common constants math sin( math pi sinetangentcosine math sqrt( )math sqrt( ( square root pow( ) * * ( exponentiation (powerabs(- )sum(( )( absolute valuesummation min( )max( ( minimummaximum the sum function shown here works on sequence of numbersand min and max accept either sequence or individual arguments there are variety of ways to drop the decimal digits of floating-point numbers we met truncation and floor earlierwe can also roundboth numerically and for display purposesmath floor( )math floor(- ( - floor (next-lower integermath trunc( )math trunc(- ( - truncate (drop decimal digitsint( )int(- ( - truncate (integer conversionround( )round( )round( round (python versionnumbers in action
732
' '{ }format( (' '' 'round for display (as we saw earlierthe last of these produces strings that we would usually print and supports variety of formatting options as also described earlierthe second-to-last test here will also output ( prior to and if we wrap it in print call to request more user-friendly display string formatting is still subtly differentthougheven in xround rounds and drops decimal digits but still produces floating-point number in memorywhereas string formatting produces stringnot number( )round( )(' ( )( ' 'interestinglythere are three ways to compute square roots in pythonusing module functionan expressionor built-in function (if you're interested in performancewe will revisit these in an exercise and its solution at the end of part ivto see which runs quicker)import math math sqrt( * pow( math sqrt( * pow( module expression built-in larger numbers notice that standard library modules such as math must be importedbut built-in functions such as abs and round are always available without imports in other wordsmodules are external componentsbut built-in functions live in an implied namespace that python automatically searches to find names used in your program this namespace simply corresponds to the standard library module called builtins in python (and __builtin__ in xthere is much more about name resolution in the function and module parts of this bookfor nowwhen you hear "module,think "import the standard library random module must be imported as well this module provides an array of toolsfor tasks such as picking random floating-point number between and and selecting random integer between two numbersimport random random random( random random( numeric types random floatsintegerschoicesshuffles
733
random randint( this module can also choose an item at random from sequenceand shuffle list of items randomlyrandom choice(['life of brian''holy grail''meaning of life']'holy grailrandom choice(['life of brian''holy grail''meaning of life']'life of briansuits ['hearts''clubs''diamonds''spades'random shuffle(suitssuits ['spades''hearts''diamonds''clubs'random shuffle(suitssuits ['clubs''diamonds''hearts''spades'though we' need additional code to make this more tangible herethe random module can be useful for shuffling cards in gamespicking images at random in slideshow guiperforming statistical simulationsand much more we'll deploy it again later in this book ( in ' permutations case study)but for more detailssee python' library manual other numeric types so far in this we've been using python' core numeric types--integerfloating pointand complex these will suffice for most of the number crunching that most programmers will ever need to do python comes with handful of more exotic numeric typesthoughthat merit brief look here decimal type python introduced new core numeric typethe decimal objectformally known as decimal syntacticallyyou create decimals by calling function within an imported modulerather than running literal expression functionallydecimals are like floating-point numbersbut they have fixed number of decimal points hencedecimals are fixed-precision floating-point values for examplewith decimalswe can have floating-point value that always retains just two decimal digits furthermorewe can specify how to round or truncate the extra decimal digits beyond the object' cutoff although it generally incurs performance penalty compared to the normal floating-point typethe decimal type is well suited to representing fixed-precision quantities like sums of money and can help you achieve better numeric accuracy other numeric types
734
the last point merits elaboration as previewed briefly when we explored comparisonsfloating-point math is less than exact because of the limited space used to store values for examplethe following should yield zerobut it does not the result is close to zerobut there are not enough bits to be precise here - python on pythons prior to and printing the result to produce the user-friendly display format doesn' completely help eitherbecause the hardware related to floating-point math is inherently limited in terms of accuracy ( precisionthe following in gives the same result as the previous outputprint( - pythons howeverwith decimalsthe result can be dead-onfrom decimal import decimal decimal(' 'decimal(' 'decimal(' 'decimal(' 'decimal(' 'as shown herewe can make decimal objects by calling the decimal constructor function in the decimal module and passing in strings that have the desired number of decimal digits for the resulting object (using the str function to convert floating-point values to strings if neededwhen decimals of different precision are mixed in expressionspython converts up to the largest number of decimal digits automaticallydecimal(' 'decimal(' 'decimal(' 'decimal(' 'decimal(' 'in pythons and laterit' also possible to create decimal object from floatingpoint objectwith call of the form decimal decimal from_float( )and recent pythons allow floating-point numbers to be used directly the conversion is exact but can sometimes yield large default number of digitsunless they are fixed per the next sectiondecimal( decimal( decimal( decimal( decimal(' - 'in python and laterthe decimal module was also optimized to improve its performance radicallythe reported speedup for the new version is to xdepending on the type of program benchmarked setting decimal precision globally other tools in the decimal module can be used to set the precision of all decimal numbersarrange error handlingand more for instancea context object in this module allows for specifying precision (number of decimal digitsand rounding modes (down numeric types
735
threadimport decimal decimal decimal( decimal decimal( decimal(' 'default digits decimal getcontext(prec decimal decimal( decimal decimal( decimal(' 'fixed precision decimal( decimal( decimal( decimal( decimal(' - 'closer to this is especially useful for monetary applicationswhere cents are represented as two decimal digits decimals are essentially an alternative to manual rounding and string formatting in this context this has more digits in memory than displayed in decimal getcontext(prec pay decimal decimal(str( )pay decimal(' 'decimal context manager in python and and laterit' also possible to reset precision temporarily by using the with context manager statement the precision is reset to its original value on statement exitin new python session (per the here is python' interactive prompt for continuation lines in some interfaces and requires manual indentationidle omits this prompt and indents for you) :\codec:\python \python import decimal decimal decimal(' 'decimal decimal(' 'decimal(' 'with decimal localcontext(as ctxctx prec decimal decimal(' 'decimal decimal(' 'decimal(' 'decimal decimal(' 'decimal decimal(' 'decimal(' 'though usefulthis statement requires much more background knowledge than you've obtained at this pointwatch for coverage of the with statement in because use of the decimal type is still relatively rare in practicei'll defer to python' standard library manuals and interactive help for more details and because decimals other numeric types
736
on to the next section to see how the two compare fraction type python and debuted new numeric typefractionwhich implements rational number object it essentially keeps both numerator and denominator explicitlyso as to avoid some of the inaccuracies and limitations of floating-point math like decimalsfractions do not map as closely to computer hardware as floating-point numbers this means their performance may not be as goodbut it also allows them to provide extra utility in standard tool where required or useful fraction basics fraction is functional cousin to the decimal fixed-precision type described in the prior sectionas both can be used to address the floating-point type' numerical inaccuracies it' also used in similar ways--like decimalfraction resides in moduleimport its constructor and pass in numerator and denominator to make one (among other schemesthe following interaction shows howfrom fractions import fraction fraction( fraction( numeratordenominator simplified to by gcd fraction( fraction( print( / once createdfractions can be used in mathematical expressions as usualx fraction( fraction(- fraction( results are exactnumeratordenominator fraction objects can also be created from floating-point number stringsmuch like decimalsfraction( 'fraction( fraction(' 'fraction( fraction( 'fraction(' 'fraction( numeric types
737
notice that this is different from floating-point-type mathwhich is constrained by the underlying limitations of floating-point hardware to comparehere are the same operations run with floating-point objectsand notes on their limited accuracy--they may display fewer digits in recent pythons than they used tobut they still aren' exact values in memorya only as accurate as floating-point hardware can lose precision over many calculations - this floating-point limitation is especially apparent for values that cannot be represented accurately given their limited number of bits in memory both fraction and decimal provide ways to get exact resultsalbeit at the cost of some speed and code verbosity for instancein the following example (repeated from the prior section)floating-point numbers do not accurately give the zero answer expectedbut both of the other types do - this should be zero (closebut not exactfrom fractions import fraction fraction( fraction( fraction( fraction( fraction( from decimal import decimal decimal(' 'decimal(' 'decimal(' 'decimal(' 'decimal(' 'moreoverfractions and decimals both allow more intuitive and accurate results than floating points sometimes canin different ways--by using rational representation and by limiting precision use in python for true "/fraction( fraction( numeric accuracytwo ways import decimal decimal getcontext(prec decimal( decimal( decimal(' 'other numeric types
738
the preceding interaction( ( use in python for true "/fraction( fraction( automatically simplified fraction( fraction( fraction( decimal decimal(str( / )decimal decimal(str( / )decimal(' ' - fraction( fraction( substantially simplerfraction conversions and mixed types to support fraction conversionsfloating-point objects now have method that yields their numerator and denominator ratiofractions have from_float methodand float accepts fraction as an argument trace through the following interaction to see how this pans out (the in the second test is special syntax that expands tuple into individual argumentsmore on this when we study function argument passing in )( as_integer_ratio(( fraction(* as_integer_ratio() fraction( float object method convert float -fractiontwo args same as fraction( fraction( fraction( from prior interaction float( float( float( convert fraction -float fraction from_float( fraction( convert float -fractionother way numeric types / / / /
739
fraction( finallysome type mixing is allowed in expressionsthough fraction must sometimes be manually propagated to retain accuracy study the following interaction to see how this worksx fraction( fraction( ( / ( / fraction( fraction( fraction int -fraction fraction float -float fraction float -float fraction fraction -fraction caveatalthough you can convert from floating point to fractionin some cases there is an unavoidable precision loss when you do sobecause the number is inaccurate in its original floating-point form when neededyou can simplify such results by limiting the maximum denominator value ( as_integer_ratio(( precision loss from float fraction( fraction(*( as_integer_ratio() fraction( (or close to it! limit_denominator( fraction( simplify to closest fraction for more details on the fraction typeexperiment further on your own and consult the python and library manuals and other documentation sets besides decimalspython also introduced new collection typethe set--an unordered collection of unique and immutable objects that supports operations corresponding to mathematical set theory by definitionan item appears only once in setno matter how many times it is added accordinglysets have variety of applicationsespecially in numeric and database-focused work other numeric types
740
such as lists and dictionaries that are outside the scope of this for examplesets are iterablecan grow and shrink on demandand may contain variety of object types as we'll seea set acts much like the keys of valueless dictionarybut it supports extra operations howeverbecause sets are unordered and do not map keys to valuesthey are neither sequence nor mapping typesthey are type category unto themselves moreoverbecause sets are fundamentally mathematical in nature (and for many readersmay seem more academic and be used much less often than more pervasive objects like dictionaries)we'll explore the basic utility of python' set objects here set basics in python and earlier there are few ways to make sets todaydepending on which python you use since this book covers alllet' begin with the case for and earlierwhich also is available (and sometimes still requiredin later pythonswe'll refine this for and extensions in moment to make set objectpass in sequence or other iterable object to the built-in set functionx set('abcde' set('bdxyz'you get back set objectwhich contains all the items in the object passed in (notice that sets do not have positional orderingand so are not sequences--their order is arbitrary and may vary per python release) set([' '' '' '' '' ']pythons < display format sets made this way support the common mathematical set operations with expression operators note that we can' perform the following operations on plain sequences like stringslistsand tuples--we must create sets from them by passing them to set in order to apply these toolsx set([' '' '' ']difference set([' '' '' '' '' '' '' '' ']union set([' '' ']intersection set([' '' '' '' '' '' ']symmetric difference (xorx yx (falsefalsesupersetsubset the notable exception to this rule is the in set membership test--this expression is also defined to work on all other collection typeswhere it also performs membership (or numeric types
741
things like strings and lists to sets to run this test'ein true membership (sets'ein 'camelot' in [ (truetruebut works on other types too in addition to expressionsthe set object provides methods that correspond to these operations and moreand that support set changes--the set add method inserts one itemupdate is an in-place unionand remove deletes an item by value (run dir call on any set instance or the set type name to see all the available methodsassuming and are still as they were in the prior interactionz intersection(yz set([' '' '] add('spam' set([' '' ''spam'] update(set([' '' ']) set([' '' '' '' ''spam'] remove(' ' set([' '' '' ''spam']same as insert one item mergein-place union delete one item as iterable containerssets can also be used in operations such as lenfor loopsand list comprehensions because they are unorderedthoughthey don' support sequence operations like indexing and slicingfor item in set('abc')print(item aaa ccc bbb finallyalthough the set expressions shown earlier generally require two setstheir method-based counterparts can often work with any iterable type as wells set([ ] set([ ]expressions require both to be sets set([ ] [ typeerrorunsupported operand type(sfor |'setand 'lists union([ ]but their methods allow any iterable set([ ] intersection(( )set([ ] issubset(range(- )true other numeric types
742
book although set operations can be coded manually in python with other typeslike lists and dictionaries (and often were in the past)python' built-in sets use efficient algorithms and implementation techniques to provide quick and standard operation set literals in python and if you think sets are "cool,they eventually became noticeably coolerwith new syntax for set literals and comprehensions initially added in the python line onlybut backported to python by popular demand in these pythons we can still use the set builtin to make set objectsbut also new set literal formusing the curly braces formerly reserved for dictionaries in and the following are equivalentset([ ]{ built-in call (allnewer set literals ( xthis syntax makes sensegiven that sets are essentially like valueless dictionaries-because set' items are unordereduniqueand immutablethe items behave much like dictionary' keys this operational similarity is even more striking given that dictionary key lists in are view objectswhich support set-like behavior such as intersections and unions (see for more on dictionary view objectsregardless of how set is made displays it using the new literal format python accepts the new literal syntaxbut still displays sets using the display form of the prior section in all pythonsthe set built-in is still required to create empty sets and to build sets from existing iterable objects (short of using set comprehensionsdiscussed later in this but the new literal is convenient for initializing sets of known structure here' what sets look like in xit' the same in except that set results display with ' set(]notationand item order may vary per version (which by definition is irrelevant in sets anyhow) :\codec:\python \python set([ ]{ set('spam'{' '' '' '' 'built-insame as in add all items in an iterable { { {' '' '' '' ' {' '' '' '' 'set literalsnew in (and add('alot' {' '' '' ''alot'' 'methods work as before all the set processing operations discussed in the prior section work the same in xbut the result sets print differently numeric types
743
{ { { { { { { true intersection union difference superset note that {is still dictionary in all pythons empty sets must be created with the set built-inand print the same ways { set(type({}empty sets print differently set( add( { initialize an empty set because {is an empty dictionary as in python and earliersets created with / literals support the same methodssome of which allow general iterable operands that expressions do not{ { { { [ typeerrorunsupported operand type(sfor |'setand 'list{ union([ ]{ { union({ }{ { union(set([ ]){ { intersection(( ){ { issubset(range(- )true immutable constraints and frozen sets sets are powerful and flexible objectsbut they do have one constraint in both and that you should keep in mind--largely because of their implementationsets can only contain immutable ( "hashable"object types hencelists and dictionaries cannot be embedded in setsbut tuples can if you need to store compound values tuples compare by their full values when used in set operationss { add([ ]typeerrorunhashable type'listonly immutable objects work in set other numeric types
744
typeerrorunhashable type'dicts add(( ) { ( ) {( )( ){ ( )( )( in true ( in false no list or dictbut tuple ok unionsame as unionmembershipby complete values tuples in setfor instancemight be used to represent datesrecordsip addressesand so on (more on tuples later in this part of the booksets may also contain modulestype objectsand more sets themselves are mutable tooand so cannot be nested in other sets directlyif you need to store set inside another setthe frozenset built-in call works just like set but creates an immutable set that cannot change and thus can be embedded in other sets set comprehensions in python and in addition to literalspython grew set comprehension construct that was backported for use to python too like the set literal accepts its syntaxbut displays its results in set notation the set comprehension expression is similar in form to the list comprehension we previewed in but is coded in curly braces instead of square brackets and run to make set instead of list set comprehensions run loop and collect the result of an expression on each iterationa loop variable gives access to the current iteration value for use in the collection expression the result is new set you create by running the codewith all the normal set behavior here is set comprehension in (againresult display and order differs in ){ * for in [ ]{ / set comprehension in this expressionthe loop is coded on the rightand the collection expression is coded on the left ( * as for list comprehensionswe get back pretty much what this expression says"give me new set containing squaredfor every in list comprehensions can also iterate across other kinds of objectssuch as strings (the first of the following examples illustrates the comprehension-based way to make set from an existing iterable){ for in 'spam'{' '' '' '' 'same asset('spam'{ for in 'spam'{'pppp''aaaa''ssss''mmmm'{ for in 'spamham'{'pppp''aaaa''hhhh''ssss''mmmm'set of collected expression results { for in 'spam' numeric types
745
{'pppp''xxxx''mmmm''aaaa''ssss' {'mmmm''xxxx'{'mmmm'because the rest of the comprehensions story relies upon underlying concepts we're not yet prepared to addresswe'll postpone further details until later in this book in we'll meet first cousin in and the dictionary comprehensionand 'll have much more to say about all comprehensions--listsetdictionaryand generator--later onespecially in and as we'll learn thereall comprehensions support additional syntax not shown hereincluding nested loops and if testswhich can be challenging to understand until you've had chance to study larger statements why setsset operations have variety of common usessome more practical than mathematical for examplebecause items are stored only once in setsets can be used to filter duplicates out of other collectionsthough items may be reordered in the process because sets are unordered in general simply convert the collection to setand then convert it back again (sets work in the list call here because they are iterableanother technical artifact that we'll unearth later) [ set( { list(set( ) [ list(set(['yy''cc''aa''xx''dd''aa'])['cc''xx''yy''dd''aa'remove duplicates but order may change sets can be used to isolate differences in listsstringsand other iterable objects too-simply convert to sets and take the difference--though again the unordered nature of sets means that the results may not match that of the originals the last two of the following compare attribute lists of string object types in (results vary in )set([ ]set([ ]{ set('abcdefg'set('abdghij'{' '' '' 'set('spam'set([' '' '' ']{' '' 'find list differences find string differences find differencesmixed set(dir(bytes)set(dir(bytearray)in bytes but not bytearray {'__getnewargs__'set(dir(bytearray)set(dir(bytes){'append''copy''__alloc__''__imul__''remove''pop''insert'more you can also use sets to perform order-neutral equality tests by converting to set before the testbecause order doesn' matter in set more formallytwo sets are equal if and other numeric types
746
the otherregardless of order for instanceyou might use this to compare the outputs of programs that should work the same but may generate results in different order sorting before testing has the same effect for equalitybut sets don' rely on an expensive sortand sorts order their results to support additional magnitude tests that sets do not (greaterlessand so on) [ ][ = order matters in sequences false set( =set( order-neutral equality true sorted( =sorted( similar but results ordered true 'spam='asmp'set('spam'=set('asmp')sorted('spam'=sorted('asmp'(falsetruetruesets can also be used to keep track of where you've already been when traversing graph or other cyclic structure for examplethe transitive module reloader and inheritance tree lister examples we'll study in and respectivelymust keep track of items visited to avoid loopsas discusses in the abstract using list in this context is inefficient because searches require linear scans although recording states visited as keys in dictionary is efficientsets offer an alternative that' essentially equivalent (and may be more or less intuitivedepending on whom you askfinallysets are also convenient when you're dealing with large data sets (database query resultsfor example)--the intersection of two sets contains objects common to both categoriesand the union contains all items in either set to illustratehere' somewhat more realistic example of set operations at workapplied to lists of people in hypothetical companyusing / set literals and result displays (use set in and earlier)engineers {'bob''sue''ann''vic'managers {'tom''sue''bobin engineers true is bob an engineerengineers managers {'sue'who is both engineer and managerengineers managers {'bob''tom''sue''vic''ann'all people in either category engineers managers {'vic''ann''bob'engineers who are not managers managers engineers {'tom'managers who are not engineers engineers managers false are all managers engineers(superset numeric types
747
true are both engineers(subset(managers engineersmanagers true all people is superset of managers managers engineers {'tom''vic''ann''bob'who is in one but not both(managers engineers(managers engineers{'sue'intersectionyou can find more details on set operations in the python library manual and some mathematical and relational database theory texts also stay tuned for ' revival of some of the set operations we've seen herein the context of dictionary view objects in python booleans some may argue that the python boolean typeboolis numeric in nature because its two valuestrue and falseare just customized versions of the integers and that print themselves differently although that' all most programmers need to knowlet' explore this type in bit more detail more formallypython today has an explicit boolean data type called boolwith the values true and false available as preassigned built-in names internallythe names true and false are instances of boolwhich is in turn just subclass (in the objectoriented senseof the built-in integer type int true and false behave exactly like the integers and except that they have customized printing logic--they print themselves as the words true and falseinstead of the digits and bool accomplishes this by redefining str and repr string formats for its two objects because of this customizationthe output of boolean expressions typed at the interactive prompt prints as the words true and false instead of the older and less obvious and in additionbooleans make truth values more explicit in your code for instancean infinite loop can now be coded as while trueinstead of the less intuitive while similarlyflags can be initialized more clearly with flag false we'll discuss these statements further in part iii againthoughfor most practical purposesyou can treat true and false as though they are predefined variables set to integers and most programmers had been preassigning true and false to and anywaythe bool type simply makes this standard its implementation can lead to curious resultsthough because true is just the integer with custom display formattrue yields integer in pythontype(trueisinstance(trueinttrue other numeric types
748
true true is false true or false true true same value but different objectsee the next same as or (hmmmsince you probably won' come across an expression like the last of these in real python codeyou can safely ignore any of its deeper metaphysical implications we'll revisit booleans in to define python' notion of truthand again in to see how boolean operators like and and or work numeric extensions finallyalthough python core numeric types offer plenty of power for most applicationsthere is large library of third-party open source extensions available to address more focused needs because numeric programming is popular domain for pythonyou'll find wealth of advanced tools for exampleif you need to do serious number crunchingan optional extension for python called numpy (numeric pythonprovides advanced numeric programming toolssuch as matrix data typevector processingand sophisticated computation libraries hardcore scientific programming groups at places like los alamos and nasa use python with numpy to implement the sorts of tasks they previously coded in ++fortranor matlab the combination of python and numpy is often compared to freemore flexible version of matlab--you get numpy' performanceplus the python language and its libraries because it' so advancedwe won' talk further about numpy in this book you can find additional support for advanced numeric programming in pythonincluding graphics and plotting toolsextended precision floatsstatistics librariesand the popular scipy package by searching the web also note that numpy is currently an optional extensionit doesn' come with python and must be installed separatelythough you'll probably want to do so if you care enough about this domain to look it up on the web summary this has taken tour of python' numeric object types and the operations we can apply to them along the waywe met the standard integer and floating-point typesas well as some more exotic and less commonly used types such as complex numbersdecimalsfractionsand sets we also explored python' expression syntaxtype conversionsbitwise operationsand various literal forms for coding numbers in scripts numeric types
749
details about the next object type--the string in the next howeverwe'll take some time to explore the mechanics of variable assignment in more detail than we have here this turns out to be perhaps the most fundamental idea in pythonso make sure you check out the next before moving on firstthoughit' time to take the usual quiz test your knowledgequiz what is the value of the expression ( in python what is the value of the expression in python what is the value of the expression in python what tools can you use to find number' square rootas well as its square what is the type of the result of the expression how can you truncate and round floating-point number how can you convert an integer to floating-point number how would you display an integer in octalhexadecimalor binary notation how might you convert an octalhexadecimalor binary string to plain integertest your knowledgeanswers the value will be the result of because the parentheses force the addition to happen before the multiplication the value will be the result of python' operator precedence rules are applied in the absence of parenthesesand multiplication has higher precedence than ( happens beforeadditionper table - this expression yields the result of for the same precedence reasons as in the prior question functions for obtaining the square rootas well as pitangentsand moreare available in the imported math module to find number' square rootimport math and call math sqrt(nto get number' squareuse either the exponent expression * or the built-in function pow( either of these last two can also compute the square root when given power of ( * the result will be floating-point numberthe integers are converted up to floating pointthe most complex type in the expressionand floating-point math is used to evaluate it the int(nand math trunc(nfunctions truncateand the round(ndigitsfunction rounds we can also compute the floor with math floor(nand round for display with string formatting operations test your knowledgeanswers
750
with floating point within an expression will result in conversion as well in some sensepython division converts too--it always returns floating-point result that includes the remaindereven if both operands are integers the oct(iand hex(ibuilt-in functions return the octal and hexadecimal string forms for an integer the bin(icall also returns number' binary digits string in pythons and later the string formatting expression and format string method also provide targets for some such conversions the int(sbasefunction can be used to convert from octal and hexadecimal strings to normal integers (pass in or for the basethe eval(sfunction can be used for this purpose toobut it' more expensive to run and can have security issues note that integers are always stored in binary form in computer memorythese are just display string format conversions numeric types
751
the dynamic typing interlude in the prior we began exploring python' core object types in depth by studying python numeric types and operations we'll resume our object type tour in the next but before we move onit' important that you get handle on what may be the most fundamental idea in python programming and is certainly the basis of much of both the conciseness and flexibility of the python language--dynamic typingand the polymorphism it implies as you'll see here and throughout this bookin pythonwe do not declare the specific types of the objects our scripts use in factmost programs should not even care about specific typesin exchangethey are naturally applicable in more contexts than we can sometimes even plan ahead for because dynamic typing is the root of this flexibilityand is also potential stumbling block for newcomerslet' take brief side trip to explore the model here the case of the missing declaration statements if you have background in compiled or statically typed languages like cc++or javayou might find yourself bit perplexed at this point in the book so farwe've been using variables without declaring their existence or their typesand it somehow works when we type in an interactive session or program filefor instancehow does python know that should stand for an integerfor that matterhow does python know what is at allonce you start asking such questionsyou've crossed over into the domain of python' dynamic typing model in pythontypes are determined automatically at runtimenot in response to declarations in your code this means that you never declare variables ahead of time ( concept that is perhaps simpler to grasp if you keep in mind that it all boils down to variablesobjectsand the links between them
752
as you've seen in many of the examples used so far in this bookwhen you run an assignment statement such as in pythonit works even if you've never told python to use the name as variableor that should stand for an integer-type object in the python languagethis all pans out in very natural wayas followsvariable creation variable ( name)like ais created when your code first assigns it value future assignments change the value of the already created name technicallypython detects some names before your code runsbut you can think of it as though initial assignments make variables variable types variable never has any type information or constraints associated with it the notion of type lives with objectsnot names variables are generic in naturethey always simply refer to particular object at particular point in time variable use when variable appears in an expressionit is immediately replaced with the object that it currently refers towhatever that may be furtherall variables must be explicitly assigned before they can be usedreferencing unassigned variables results in errors in sumvariables are created when assignedcan reference any type of objectand must be assigned before they are referenced this means that you never need to declare names used by your scriptbut you must initialize names before you can update themcountersfor examplemust be initialized to zero before you can add to them this dynamic typing model is strikingly different from the typing model of traditional languages when you are first starting outthe model is usually easier to understand if you keep clear the distinction between names and objects for examplewhen we say this to assign variable valuea assign name to an object at least conceptuallypython will perform three distinct steps to carry out the request these steps reflect the operation of all assignments in the python language create an object to represent the value create the variable aif it does not yet exist link the variable to the new object the net result will be structure inside python that resembles figure - as sketchedvariables and objects are stored in different parts of memory and are associated by links (the link is shown as pointer in the figurevariables always link to objects and never to other variablesbut larger objects may link to other objects (for instancea list object has links to the objects it contains the dynamic typing interlude
753
the object internallythe variable is really pointer to the object' memory space created by running the literal expression these links from variables to objects are called references in python--that isa reference is kind of associationimplemented as pointer in memory whenever the variables are later used ( referenced)python automatically follows the variable-to-object links this is all simpler than the terminology may imply in concrete termsvariables are entries in system tablewith spaces for links to objects objects are pieces of allocated memorywith enough space to represent the values for which they stand references are automatically followed pointers from variables to objects at least conceptuallyeach time you generate new value in your script by running an expressionpython creates new object ( chunk of memoryto represent that value as an optimizationpython internally caches and reuses certain kinds of unchangeable objectssuch as small integers and strings (each is not really new piece of memory--more on this caching behavior laterbut from logical perspectiveit works as though each expression' result value is distinct object and each object is distinct piece of memory technically speakingobjects have more structure than just enough space to represent their values each object also has two standard header fieldsa type designator used to mark the type of the objectand reference counter used to determine when it' ok to reclaim the object to understand how these two header fields factor into the modelwe need to move on types live with objectsnot variables to see how object types come into playwatch what happens if we assign variable multiple times readers with background in may find python references similar to pointers (memory addressesin factreferences are implemented as pointersand they often serve the same rolesespecially with objects that can be changed in place (more on this laterhoweverbecause references are always automatically dereferenced when usedyou can never actually do anything useful with reference itselfthis is feature that eliminates vast category of bugs but you can think of python references as "void*pointerswhich are automatically followed whenever used the case of the missing declaration statements
754
'spama it' an integer now it' string now it' floating point this isn' typical python codebut it does work-- starts out as an integerthen becomes stringand finally becomes floating-point number this example tends to look especially odd to ex- programmersas it appears as though the type of changes from integer to string when we say 'spamhoweverthat' not really what' happening in pythonthings work more simply names have no typesas stated earliertypes live with objectsnot names in the preceding listingwe've simply changed to reference different objects because variables have no typewe haven' actually changed the type of the variable awe've simply made the variable reference different type of object in factagainall we can ever say about variable in python is that it references particular object at particular point in time objectson the other handknow what type they are--each object contains header field that tags the object with its type the integer object for examplewill contain the value plus designator that tells python that the object is an integer (strictly speakinga pointer to an object called intthe name of the integer typethe type designator of the 'spamstring object points to the string type (called strinstead because objects know their typesvariables don' have to to recaptypes are associated with objects in pythonnot with variables in typical codea given variable usually will reference just one kind of object because this isn' requirementthoughyou'll find that python code tends to be much more flexible than you may be accustomed to--if you use python wellyour code might work on many types automatically mentioned that objects have two header fieldsa type designator and reference counter to understand the latter of thesewe need to move on and take brief look at what happens at the end of an object' life objects are garbage-collected in the prior section' listingswe assigned the variable to different types of objects in each assignment but when we reassign variablewhat happens to the value it was previously referencingfor exampleafter the following statementswhat happens to the object 'spamthe answer is that in pythonwhenever name is assigned to new objectthe space held by the prior object is reclaimed if it is not referenced by any other name or object this automatic reclamation of objectsspace is known as garbage collectionand makes life much simpler for programmers of languages like python that support it the dynamic typing interlude
755
to illustrateconsider the following examplewhich sets the name to different object on each assignmentx 'shrubberyx [ reclaim now (unless referenced elsewherereclaim 'shrubberynow reclaim now firstnotice that is set to different type of object each time againthough this is not really the casethe effect is as though the type of is changing over time rememberin python types live with objectsnot names because names are just generic references to objectsthis sort of code works naturally secondnotice that references to objects are discarded along the way each time is assigned to new objectpython reclaims the prior object' space for instancewhen it is assigned the string 'shrubbery'the object is immediately reclaimed (assuming it is not referenced anywhere else)--that isthe object' space is automatically thrown back into the free space poolto be reused for future object internallypython accomplishes this feat by keeping counter in every object that keeps track of the number of references currently pointing to that object as soon as (and exactly whenthis counter drops to zerothe object' memory space is automatically reclaimed in the preceding listingwe're assuming that each time is assigned to new objectthe prior object' reference counter drops to zerocausing it to be reclaimed the most immediately tangible benefit of garbage collection is that it means you can use objects liberally without ever needing to allocate or free up space in your script python will clean up unused space for you as your program runs in practicethis eliminates substantial amount of bookkeeping code required in lower-level languages such as and +more on python garbage collection technically speakingpython' garbage collection is based mainly upon reference countersas described herehoweverit also has component that detects and reclaims objects with cyclic references in time this component can be disabled if you're sure that your code doesn' create cyclesbut it is enabled by default circular references are classic issue in reference count garbage collectors because references are implemented as pointersit' possible for an object to reference itselfor reference another object that does for exampleexercise at the end of part and its solution in appendix show how to create cycle easily by embedding reference to list within itself ( append( )the same phenomenon can occur for assignments to attributes of objects created from user-defined classes though relatively rarebecause the reference counts for such objects never drop to zerothey must be treated specially for more details on python' cycle detectorsee the documentation for the gc module in python' library manual the best news here is that garbage-collection-based memory management is implemented for you in pythonby people highly skilled at the task the case of the missing declaration statements
756
standard python ( cpythononly' alternative implementations such as jythonironpythonand pypy may use different schemesthough the net effect in all is similar--unused space is reclaimed for you automaticallyif not always as immediately shared references so farwe've seen what happens as single variable is assigned references to objects now let' introduce another variable into our interaction and watch what happens to its names and objectsa typing these two statements generates the scene captured in figure - the second command causes python to create the variable bthe variable is being used and not assigned hereso it is replaced with the object it references ( )and is made to reference that object the net effect is that the variables and wind up referencing the same object (that ispointing to the same chunk of memoryfigure - names and objects after next running the assignment variable becomes reference to the object internallythe variable is really pointer to the object' memory space created by running the literal expression this scenario in python--with multiple names referencing the same object--is usually called shared reference (and sometimes just shared objectnote that the names and are not linked to each other directly when this happensin factthere is no way to ever link variable to another variable in python ratherboth variables point to the same object via their references nextsuppose we extend the session with one more statementa 'spamas with all python assignmentsthis statement simply makes new object to represent the string value 'spamand sets to reference this new object it does nothowever the dynamic typing interlude
757
the new object ( piece of memorycreated by running the literal expression 'spam'but variable still refers to the original object because this assignment is not an in-place change to the object it changes only variable anot change the value of bb still references the original objectthe integer the resulting reference structure is shown in figure - the same sort of thing would happen if we changed to 'spaminstead--the assignment would change only bnot this behavior also occurs if there are no type differences at all for exampleconsider these three statementsa in this sequencethe same events transpire python makes the variable reference the object and makes reference the same object as aas in figure - as beforethe last assignment then sets to completely different object (in this casethe integer which is the result of the expressionit does not change as side effect in factthere is no way to ever overwrite the value of the object --as introduced in integers are immutable and thus can never be changed in place one way to think of this is thatunlike in some languagesin python variables are always pointers to objectsnot labels of changeable memory areassetting variable to new value does not alter the original objectbut rather causes the variable to reference an entirely different object the net effect is that assignment to variable itself can impact only the single variable being assigned when mutable objects and in-place changes enter the equationthoughthe picture changes somewhatto see howlet' move on shared references and in-place changes as you'll see later in this part' there are objects and operations that perform in-place object changes--python' mutable typesincluding listsdictionariesand sets for instancean assignment to an offset in list actually changes the list object itself in placerather than generating brand-new list object shared references
758
can matter much in your programs for objects that support such in-place changesyou need to be more aware of shared referencessince change from one name may impact others otherwiseyour objects may seem to change for no apparent reason given that all assignments are based on references (including function argument passing)it' pervasive potential to illustratelet' take another look at the list objects introduced in recall that listswhich do support in-place assignments to positionsare simply collections of other objectscoded in square bracketsl [ here is list containing the objects and items inside list are accessed by their positionsso [ refers to object the first item in the list of courselists are also objects in their own rightjust like integers and strings after running the two prior assignmentsl and reference the same shared objectjust like and in the prior example (see figure - now say thatas beforewe extend this interaction to say the followingl this assignment simply sets to different objectl still references the original list if we change this statement' syntax slightlyhoweverit has radically different effectl [ [ mutable object make reference to the same object an in-place change [ [ is different but so is reallywe haven' changed itself herewe've changed component of the object that references this sort of change overwrites part of the list object' value in place because the list object is shared by (referenced fromother variablesthoughan inplace change like this doesn' affect only --that isyou must be aware that when you make such changesthey can impact other parts of your program in this examplethe effect shows up in as well because it references the same object as againwe haven' actually changed eitherbut its value will appear different because it refers to an object that has been overwritten in place this behavior only occurs for mutable objects that support in-place changesand is usually what you wantbut you should be aware of how it worksso that it' expected it' also just the defaultif you don' want such behavioryou can request that python copy objects instead of making references there are variety of ways to copy listincluding using the built-in list function and the standard library copy module perhaps the dynamic typing interlude
759
more on slicing) [ [: [ [ [ make copy of (or list( )copy copy( )etc is not changed herethe change made through is not reflected in because references copy of the object referencesnot the originalthat isthe two variables point to different pieces of memory note that this slicing technique won' work on the other major mutable core typesdictionaries and setsbecause they are not sequences--to copy dictionary or setinstead use their copy(method call (lists have one as of python as well)or pass the original object to their type namesdict and set alsonote that the standard library copy module has call for copying any object type genericallyas well as call for copying nested object structures-- dictionary with nested listsfor exampleimport copy copy copy(yx copy deepcopy(ymake top-level "shallowcopy of any object make deep copy of any object ycopy all nested parts we'll explore lists and dictionaries in more depthand revisit the concept of shared references and copiesin and for nowkeep in mind that objects that can be changed in place (that ismutable objectsare always open to these kinds of effects in any code they pass through in pythonthis includes listsdictionariessetsand some objects defined with class statements if this is not the desired behavioryou can simply copy your objects as needed shared references and equality in the interest of full disclosurei should point out that the garbage-collection behavior described earlier in this may be more conceptual than literal for certain types consider these statementsx 'shrubberyreclaim nowbecause python caches and reuses small integers and small stringsas mentioned earlierthe object here is probably not literally reclaimedinsteadit will likely remain in system table to be reused the next time you generate in your code most kinds of objectsthoughare reclaimed immediately when they are no longer referencedfor those that are notthe caching mechanism is irrelevant to your code for instancebecause of python' reference modelthere are two different ways to check for equality in python program let' create shared reference to demonstrateshared references
760
= true is true and reference the same object same values same objects the first technique herethe =operatortests whether the two referenced objects have the same valuesthis is the method almost always used for equality checks in python the second methodthe is operatorinstead tests for object identity--it returns true only if both names point to the exact same objectso it is much stronger form of equality testing and is rarely applied in most programs reallyis simply compares the pointers that implement referencesand it serves as way to detect shared references in your code if needed it returns false if the names point to equivalent but different objectsas is the case when we run two different literal expressionsl [ [ = true is false and reference different objects same values different objects nowwatch what happens when we perform the same operations on small numbersx = true is true should be two different objects same object anyhowcaching at workin this interactionx and should be =(same value)but not is (same objectbecause we ran two different literal expressions ( because small integers and strings are cached and reusedthoughis tells us they reference the same single object in factif you really want to look under the hoodyou can always ask python how many references there are to an objectthe getrefcount function in the standard sys module returns the object' reference count when ask about the integer object in the idle guifor instanceit reports reuses of this same object (most of which are in idle' system codenot minethough this returns outside idle so python must be hoarding as well)import sys sys getrefcount( pointers to this shared piece of memory this object caching and reuse is irrelevant to your code (unless you run the is check!because you cannot change immutable numbers or strings in placeit doesn' matter how many references there are to the same object--every reference will always see the the dynamic typing interlude
761
dynamic typing is everywhere of courseyou don' really need to draw name/object diagrams with circles and arrows to use python when you're starting outthoughit sometimes helps you understand unusual cases if you can trace their reference structures as we've done here if mutable object changes out from under you when passed around your programfor examplechances are you are witnessing some of this subject matter firsthand moreovereven if dynamic typing seems little abstract at this pointyou probably will care about it eventually because everything seems to work by assignment and references in pythona basic understanding of this model is useful in many different contexts as you'll seeit works the same in assignment statementsfunction argumentsfor loop variablesmodule importsclass attributesand more the good news is that there is just one assignment model in pythononce you get handle on dynamic typingyou'll find that it works the same everywhere in the language at the most practical leveldynamic typing means there is less code for you to write just as importantlythoughdynamic typing is also the root of python' polymorphisma concept we introduced in and will revisit again later in this book because we do not constrain types in python codeit is both concise and highly flexible as you'll seewhen used welldynamic typing--and the polymorphism it implies-produces code that automatically adapts to new requirements as your systems evolve "weakreferences you may occasionally see the term "weak referencein the python world this is somewhat advanced toolbut is related to the reference model we've explored hereand like the is operatorcan' really be understood without it in shorta weak referenceimplemented by the weakref standard library moduleis reference to an object that does not by itself prevent the referenced object from being garbage-collected if the last remaining references to an object are weak referencesthe object is reclaimed and the weak references to it are automatically deleted (or otherwise notifiedthis can be useful in dictionary-based caches of large objectsfor exampleotherwisethe cache' reference alone would keep the object in memory indefinitely stillthis is really just special-case extension to the reference model for more detailssee python' library manual dynamic typing is everywhere
762
this took deeper look at python' dynamic typing model--that isthe way that python keeps track of object types for us automaticallyrather than requiring us to code declaration statements in our scripts along the waywe learned how variables and objects are associated by references in pythonwe also explored the idea of garbage collectionlearned how shared references to objects can affect multiple variablesand saw how references impact the notion of equality in python because there is just one assignment model in pythonand because assignment pops up everywhere in the languageit' important that you have handle on the model before moving on the following quiz should help you review some of this ideas after thatwe'll resume our core object tour in the next with strings test your knowledgequiz consider the following three statements do they change the value printed for aa "spamb "shrubbery consider these three statements do they change the printed value of aa ["spam" [ "shrubbery how about these--is changed nowa ["spam" [: [ "shrubberytest your knowledgeanswers noa still prints as "spamwhen is assigned to the string "shrubbery"all that happens is that the variable is reset to point to the new string object and initially share ( reference/point tothe same single string object "spam"but two names are never linked together in python thussetting to different object has no effect on the same would be true if the last statement here were 'shrubbery'by the way--the concatenation would make new object for its resultwhich would then be assigned to only we can never overwrite string (or numberor tuplein placebecause strings are immutable yesa now prints as ["shrubbery"technicallywe haven' really changed either or binsteadwe've changed part of the object they both reference (point toby overwriting that object in place through the variable because references the same object as bthe update is reflected in as well the dynamic typing interlude
763
time because the slice expression made copy of the list object before it was assigned to after the second assignment statementthere are two different list objects that have the same value (in pythonwe say they are ==but not isthe third statement changes the value of the list object pointed to by bbut not that pointed to by test your knowledgeanswers
764
string fundamentals so farwe've studied numbers and explored python' dynamic typing model the next major type on our in-depth core object tour is the python string--an ordered collection of characters used to store and represent textand bytes-based information we looked briefly at strings in herewe will revisit them in more depthfilling in some of the details we skipped earlier this scope before we get startedi also want to clarify what we won' be covering here briefly previewed unicode strings and files--tools for dealing with non-ascii text unicode is key tool for some programmersespecially those who work in the internet domain it can pop upfor examplein web pagesemail content and headersftp transfersgui apisdirectory toolsand htmlxml and json text at the same timeunicode can be heavy topic for programmers just starting outand many (or mostof the python programmers meet today still do their jobs in blissful ignorance of the entire topic in light of thatthis book relegates most of the unicode story to of its advanced topics part as optional readingand focuses on string basics here that isthis tells only part of the string story in python--the part that most scripts use and most programmers need to know it explores the fundamental str string typewhich handles ascii textand works the same regardless of which version of python you use despite this intentionally limited scopebecause str also handles unicode in python xand the separate unicode type works almost identically to str in xeverything we learn here will apply directly to unicode processing too unicodethe short story for readers who do care about unicodei' like to also provide quick summary of its impacts and pointers for further study from formal perspectiveascii is simple
765
from non-english-speaking sources may use very different lettersand may be encoded very differently when stored in files as we saw in python addresses this by distinguishing between text and binary datawith distinct string object types and file interfaces for each this support varies per python linein python there are three string typesstr is used for unicode text (including ascii)bytes is used for binary data (including encoded text)and bytearray is mutable variant of bytes files work in two modestextwhich represents content as str and implements unicode encodingsand binarywhich deals in raw bytes and does no data translation in python xunicode strings represent unicode textstr strings handle both bit text and binary dataand bytearray is available in and later as back-port from normal filescontent is simply bytes represented as strbut codecs module opens unicode text fileshandles encodingsand represents content as unicode objects despite such version differencesif and when you do need to care about unicode you'll find that it is relatively minor extension--once text is in memoryit' python string of characters that supports all the basics we'll study in this in factthe primary distinction of unicode often lies in the translation ( encodingstep required to move it to and from files beyond thatit' largely just string processing againthoughbecause most programmers don' need to come to grips with unicode details up fronti've moved most of them to when you're ready to learn about these more advanced string conceptsi encourage you to see both their preview in and the full unicode and bytes disclosure in after reading the string fundamentals material here for this we'll focus on the basic string type and its operations as you'll findthe techniques we'll study here also apply directly to the more advanced string types in python' toolset string basics from functional perspectivestrings can be used to represent just about anything that can be encoded as text or bytes in the text departmentthis includes symbols and words ( your name)contents of text files loaded into memoryinternet addressespython source codeand so on strings can also be used to hold the raw bytes used for media files and network transfersand both the encoded and decoded forms of nonascii unicode text used in internationalized programs you may have used strings in other languagestoo python' strings serve the same role as character arrays in languages such as cbut they are somewhat higher-level tool string fundamentals
766
tools also unlike languages such as cpython has no distinct type for individual charactersinsteadyou just use one-character strings strictly speakingpython strings are categorized as immutable sequencesmeaning that the characters they contain have left-to-right positional order and that they cannot be changed in place in factstrings are the first representative of the larger class of objects called sequences that we will study here pay special attention to the sequence operations introduced in this because they will work the same on other sequence types we'll explore latersuch as lists and tuples table - previews common string literals and operations we will discuss in this empty strings are written as pair of quotation marks (single or doublewith nothing in betweenand there are variety of ways to code strings for processingstrings support expression operations such as concatenation (combining strings)slicing (extracting sections)indexing (fetching by offset)and so on besides expressionspython also provides set of string methods that implement common string-specific tasksas well as modules for more advanced text-processing tasks such as pattern matching we'll explore all of these later in the table - common string literals and operations operation interpretation 'empty string "spam'sdouble quotessame as single ' \np\ta\ mescape sequences ""multiline ""triple-quoted block strings '\temp\spamraw strings (no escapesb 'sp\xc mbyte strings in and ( 'sp\ municode strings in and ( concatenaterepeat [iindexslicelength [ :jlen( " % parrotkind string formatting expression " { parrotformat(kindstring formatting method in and find('pa'string methods (see ahead for all )searchs rstrip(remove whitespaces replace('pa''xx'replacements split(','split on delimiterstring basics
767
isdigit(interpretation content tests lower(case conversions endswith('spam'end test'spamjoin(strlistdelimiter joins encode('latin- 'unicode encodingb decode('utf 'unicode decodingetc (see table - for in sprint(xiterationmembership 'spamin [ for in smap(ordsre match('sp*)am'linepattern matchinglibrary module beyond the core set of string tools in table - python also supports more advanced pattern-based string processing with the standard library' re (for "regular expression"moduleintroduced in and and even higher-level text processing tools such as xml parsers (discussed briefly in this book' scopethoughis focused on the fundamentals represented by table - to cover the basicsthis begins with an overview of string literal forms and string expressionsthen moves on to look at more advanced tools such as string methods and formatting python comes with many string toolsand we won' look at them all herethe complete story is chronicled in the python library manual and reference books our goal here is to explore enough commonly used tools to give you representative samplemethods we won' see in action herefor exampleare largely analogous to those we will string literals by and largestrings are fairly easy to use in python perhaps the most complicated thing about them is that there are so many ways to write them in your codesingle quotes'spa"mdouble quotes"spa'mtriple quotes''spam '''""spam ""escape sequences" \tp\na\ mraw stringsr" :\new\test spmbytes literals in and (see ) 'sp\ amunicode literals in and (see ) 'eggs\ spam string fundamentals
768
specialized rolesand we're postponing further discussion of the last two advanced forms until let' take quick look at all the other options in turn singleand double-quoted strings are the same around python stringssingleand double-quote characters are interchangeable that isstring literals can be written enclosed in either two single or two double quotes-the two forms work the same and return the same type of object for examplethe following two strings are identicalonce coded'shrubbery'"shrubbery('shrubbery''shrubbery'the reason for supporting both is that it allows you to embed quote character of the other variety inside string without escaping it with backslash you may embed single-quote character in string enclosed in double-quote charactersand vice versa'knight" '"knight' ('knight" '"knight' "this book generally prefers to use single quotes around strings just because they are marginally easier to readexcept in cases where single quote is embedded in the string this is purely subjective style choicebut python displays strings this way too and most python programmers do the same todayso you probably should too note that the comma is important here without itpython automatically concatenates adjacent string literals in any expressionalthough it is almost as simple to add operator between them to invoke concatenation explicitly (as we'll see in wrapping this form in parentheses also allows it to span multiple lines)title "meaning 'oflifetitle 'meaning of lifeimplicit concatenation adding commas between these strings would result in tuplenot string also notice in all of these outputs that python prints strings in single quotes unless they embed one if neededyou can also embed quote characters by escaping them with backslashes'knight\' '"knight\" ("knight' "'knight" 'to understand whyyou need to know how escapes work in general escape sequences represent special characters the last example embedded quote inside string by preceding it with backslash this is representative of general pattern in stringsbackslashes are used to introduce special character codings known as escape sequences string literals
769
keyboard the character \and one or more characters following it in the string literalare replaced with single character in the resulting string objectwhich has the binary value specified by the escape sequence for examplehere is five-character string that embeds newline and tabs ' \nb\tcthe two characters \ stand for single character--the binary value of the newline character in your character set (in asciicharacter code similarlythe sequence \ is replaced with the tab character the way this string looks when printed depends on how you print it the interactive echo shows the special characters as escapesbut print interprets them insteads ' \nb\tcprint(sa to be completely sure how many actual characters are in this stringuse the built-in len function--it returns the actual number of characters in stringregardless of how it is coded or displayedlen( this string is five characters longit contains an ascii aa newline characteran ascii band so on if you're accustomed to all-ascii textit' tempting to think of this result as meaning bytes toobut you probably shouldn' really"byteshas no meaning in the unicode world for one thingthe string object is probably larger in memory in python more criticallystring content and length both reflect code points (identifying numbersin unicode-speakwhere single character does not necessarily map directly to single byteeither when encoded in files or when stored in memory this mapping might hold true for simple -bit ascii textbut even this depends on both the external encoding type and the internal storage scheme used under utf- for exampleascii characters are multiple bytes in filesand they may be or bytes in memory depending on how python allocates their space for othernon-ascii textwhose charactersvalues might be too large to fit in an -bit bytethe character-to-byte mapping doesn' apply at all in fact defines str strings formally as sequences of unicode code pointsnot bytesto make this clear there' more on how strings are stored internally in if you care to know for nowto be safestthink characters instead of bytes in strings trust me on thisas an exc programmeri had to break the habit too string fundamentals
770
with the string in memorythey are used only to describe special character values to be stored in the string for coding such special characterspython recognizes full set of escape code sequenceslisted in table - table - string backslash characters escape meaning \newline ignored (continuation line\backslash (stores one \\single quote (stores '\double quote (stores "\ bell \ backspace \ formfeed \ newline (linefeed\ carriage return \ horizontal tab \ vertical tab \xhh character with hex value hh (exactly digits\ooo character with octal value ooo (up to digits\ nullbinary character (doesn' end string\nid unicode database id \uhhhh unicode character with -bit hex value \uhhhhhhhh unicode character with -bit hex valuea \other not an escape (keeps both and othera the \uhhhh escape sequence takes exactly eight hexadecimal digits ( )both \ and \ are recognized only in unicode string literals in xbut can be used in normal strings (which are unicodein in bytes literalhexadecimal and octal escapes denote the byte with the given valuein string literalthese escapes denote unicode character with the given code-point value there is more on unicode escapes in some escape sequences allow you to embed absolute binary values into the characters of string for instancehere' five-character string that embeds two characters with binary zero values (coded as octal escapes of one digit) ' \ \ cs ' \ \ clen( in pythona zero (nullcharacter like this does not terminate string the way "null bytetypically does in insteadpython keeps both the string' length and text in memory in factno character terminates string in python here' string that is all string literals
771
(coded in hexadecimal) '\ \ \ '\ \ \ len( notice that python displays nonprintable characters in hexregardless of how they were specified you can freely combine absolute value escapes and the more symbolic escape types in table - the following string contains the characters "spam" tab and newlineand an absolute zero value character coded in hexs " \tp\na\ ms ' \tp\na\ mlen( print(ss this becomes more important to know when you process binary data files in python because their contents are represented as strings in your scriptsit' ok to process binary files that contain any sorts of binary byte values--when opened in binary modesfiles return strings of raw bytes from the external file (there' much more on files in and finallyas the last entry in table - impliesif python does not recognize the character after as being valid escape codeit simply keeps the backslash in the resulting stringx " :\py\codex ' :\\py\\codelen( keeps literally (and displays it as \\howeverunless you're able to commit all of table - to memory (and there are arguably better uses for your neurons!)you probably shouldn' rely on this behavior to code literal backslashes explicitly such that they are retained in your stringsdouble them up (\is an escape for one \or use raw stringsthe next section shows how raw strings suppress escapes as we've seenescape sequences are handy for embedding special character codes within strings sometimesthoughthe special treatment of backslashes for introducing escapes can lead to trouble it' surprisingly commonfor instanceto see python newcomers in classes trying to open file with filename argument that looks something like thismyfile open(' :\new\text dat'' ' string fundamentals
772
here is that \ is taken to stand for newline characterand \ is replaced with tab in effectthe call tries to open file named :(newline)ew(tab)ext datwith usually lessthan-stellar results this is just the sort of thing that raw strings are useful for if the letter (uppercase or lowercaseappears just before the opening quote of stringit turns off the escape mechanism the result is that python retains your backslashes literallyexactly as you type them thereforeto fix the filename problemjust remember to add the letter on windowsmyfile open( ' :\new\text dat'' 'alternativelybecause two backslashes are really an escape sequence for one backslashyou can keep your backslashes by simply doubling them upmyfile open(' :\\new\\text dat'' 'in factpython itself sometimes uses this doubling scheme when it prints strings with embedded backslashespath ' :\new\text datpath ' :\\new\\text datprint(pathc:\new\text dat len(path show as python code user-friendly format string length as with numeric representationthe default format at the interactive prompt prints results as if they were codeand therefore escapes backslashes in the output the print statement provides more user-friendly format that shows that there is actually only one backslash in each spot to verify this is the caseyou can check the result of the built-in len functionwhich returns the number of characters in the stringindependent of display formats if you count the characters in the print(pathoutputyou'll see that there really is just character per backslashfor total of besides directory paths on windowsraw strings are also commonly used for regular expressions (text pattern matchingsupported with the re module introduced in and also note that python scripts can usually use forward slashes in directory paths on windows and unix because python tries to interpret paths portably ( ' :/new/text datworks when opening filestooraw strings are useful if you code paths using native windows backslashesthough string literals
773
must escape the surrounding quote character to embed it in the string that isr\is not valid string literal-- raw string cannot end in an odd number of backslashes if you need to end raw string with single backslashyou can use two and slice off the second ( ' \nb\tc\'[:- ])tack one on manually ( ' \nb\tc'\\')or skip the raw string syntax and just double up the backslashes in normal string (' \nb\\tc\\'all three of these forms create the same eight-character string containing three backslashes triple quotes code multiline block strings so faryou've seen single quotesdouble quotesescapesand raw strings in action python also has triple-quoted string literal formatsometimes called block stringthat is syntactic convenience for coding multiline text data this form begins with three quotes (of either the single or double variety)is followed by any number of lines of textand is closed with the same triple-quote sequence that opened it single and double quotes embedded in the string' text may bebut do not have to beescaped-the string does not end until python sees three unescaped quotes of the same kind used to start the literal for example (the here is python' prompt for continuation lines outside idledon' type it yourself)mantra """always look on the bright side of life ""mantra 'always look\ on the bright\nside of life this string spans three lines as we learned in in some interfacesthe interactive prompt changes to on continuation lines like thisbut idle simply drops down one linethis book shows listings in both formsso extrapolate as needed either waypython collects all the triple-quoted text into single multiline stringwith embedded newline characters (\nat the places where your code has line breaks notice thatas in the literalthe second line in the result has leading spacesbut the third does not--what you type is truly what you get to see the string with the newlines interpretedprint it instead of echoingprint(mantraalways look on the bright side of life in facttriple-quoted strings will retain all the enclosed textincluding any to the right of your code that you might intend as comments so don' do this--put your comments above or below the quoted textor use the automatic concatenation of adjacent strings mentioned earlierwith explicit newlines if desiredand surrounding parentheses to string fundamentals
774
menu """spam comments here added to stringeggs ditto ""menu 'spam comments here added to string!\neggs menu "spam\ "eggs\nmenu 'spam\neggs\nditto\ncomments here ignored but newlines not automatic triple-quoted strings are useful anytime you need multiline text in your programfor exampleto embed multiline error messages or htmlxmlor json code in your python source code files you can embed such blocks directly in your scripts by triplequoting without resorting to external text files or explicit concatenation and newline characters triple-quoted strings are also commonly used for documentation stringswhich are string literals that are taken as comments when they appear at specific points in your file (more on these later in the bookthese don' have to be triple-quoted blocksbut they usually are to allow for multiline comments finallytriple-quoted strings are also sometimes used as "horribly hackishway to temporarily disable lines of code during development (okit' not really too horribleand it' actually fairly common practice todaybut it wasn' the intentif you wish to turn off few lines of code and run your script againsimply put three quotes above and below themlike thisx ""import os print(os getcwd()"" disable this code temporarily said this was hackish because python really might make string out of the lines of code disabled this waybut this is probably not significant in terms of performance for large sections of codeit' also easier than manually adding hash marks before each line and later removing them this is especially true if you are using text editor that does not have support for editing python code specifically in pythonpracticality often beats aesthetics string literals
775
once you've created string with the literal expressions we just metyou will almost certainly want to do things with it this section and the next two demonstrate string expressionsmethodsand formatting--the first line of text-processing tools in the python language basic operations let' begin by interacting with the python interpreter to illustrate the basic string operations listed earlier in table - you can concatenate strings using the operator and repeat them using the operatorpython len('abc' 'abc'def'abcdef'ni! 'ni!ni!ni!ni!lengthnumber of items concatenationa new string repetitionlike "ni!"ni!the len built-in function here returns the length of string (or any other object with lengthformallyadding two string objects with creates new string objectwith the contents of its operands joinedand repetition with is like adding string to itself number of times in both casespython lets you create arbitrarily sized stringsthere' no need to predeclare anything in pythonincluding the sizes of data structures--you simply create string objects as needed and let python manage the underlying memory space automatically (see for more on python' memory management "garbage collector"repetition may seem bit obscure at firstbut it comes in handy in surprising number of contexts for exampleto print line of dashesyou can count up to or let python count for youprint(more ---'print('- dashesthe hard way dashesthe easy way notice that operator overloading is at work here alreadywe're using the same and operators that perform addition and multiplication when using numbers python does the correct operation because it knows the types of the objects being added and multiplied but be carefulthe rules aren' quite as liberal as you might expect for instancepython doesn' allow you to mix numbers and strings in expressions'abc'+ raises an error instead of automatically converting to string as shown in the last row in table - you can also iterate over strings in loops using for statementswhich repeat actionsand test membership for both characters and substrings with the in expression operatorwhich is essentially search for substringsin is much like the str find(method covered later in this but it returns string fundamentals
776
and may leave your cursor bit indentedin say print cinstead)myjob "hackerfor in myjobprint(cend=' "kin myjob true "zin myjob false 'spamin 'abcspamdeftrue step through itemsprint each ( formfound not found substring searchno position returned the for loop assigns variable to successive items in sequence (herea stringand executes one or more statements for each item in effectthe variable becomes cursor stepping across the string' characters here we will discuss iteration tools like these and others listed in table - in more detail later in this book (especially in and indexing and slicing because strings are defined as ordered collections of characterswe can access their components by position in pythoncharacters in string are fetched by indexing-providing the numeric offset of the desired component in square brackets after the string you get back the one-character string at the specified position as in the languagepython offsets start at and end at one less than the length of the string unlike choweverpython also lets you fetch items from sequences such as strings using negative offsets technicallya negative offset is added to the length of string to derive positive offset you can also think of negative offsets as counting backward from the end the following interaction demonstratess 'spams[ ] [- (' '' ' [ : ] [ :] [:- ('pa''pam''spa'indexing from front or end slicingextract section the first line defines four-character string and assigns it the name the next line indexes it in two wayss[ fetches the item at offset from the left--the one-character string ' ' [- gets the item at offset back from the end--or equivalentlyat offset ( (- )from the front in more graphic termsoffsets and slices map to cells as shown in figure more mathematically minded readers (and students in my classessometimes detect small asymmetry herethe leftmost item is at offset but the rightmost is at offset - alasthere is no such thing as distinct - value in python strings in action
777
negatives count back from the right end (offset - is the last itemeither kind of offset can be used to give positions in indexing and slicing operations the last line in the preceding example demonstrates slicinga generalized form of indexing that returns an entire sectionnot single item probably the best way to think of slicing is that it is type of parsing (analyzing structure)especially when applied to strings--it allows us to extract an entire section (substringin single step slices can be used to extract columns of datachop off leading and trailing textand more in factwe'll explore slicing in the context of text parsing later in this the basics of slicing are straightforward when you index sequence object such as string on pair of offsets separated by colonpython returns new object containing the contiguous section identified by the offset pair the left offset is taken to be the lower bound (inclusive)and the right is the upper bound (noninclusivethat ispython fetches all items from the lower bound up to but not including the upper boundand returns new object containing the fetched items if omittedthe left and right bounds default to and the length of the object you are slicingrespectively for instancein the example we just saws[ : extracts the items at offsets and it grabs the second and third itemsand stops before the fourth item at offset nexts[ :gets all items beyond the first--the upper boundwhich is not specifieddefaults to the length of the string finallys[:- fetches all but the last item--the lower bound defaults to and - refers to the last itemnoninclusive this may seem confusing at first glancebut indexing and slicing are simple and powerful tools to useonce you get the knack rememberif you're unsure about the effects of slicetry it out interactively in the next you'll see that it' even possible to change an entire section of another object in one step by assigning to slice (though not for immutables like stringshere' summary of the details for referenceindexing ( [ ]fetches components at offsetsthe first item is at offset negative indexes mean to count backward from the end or right [ fetches the first item [- fetches the second item from the end (like [len( )- ] string fundamentals
778
the upper bound is noninclusive slice boundaries default to and the sequence lengthif omitted [ : fetches items at offsets up to but not including [ :fetches items at offset through the end (the sequence lengths[: fetches items at offset up to but not including [:- fetches items at offset up to but not including the last item [:fetches items at offsets through the end--making top-level copy of extended slicing ( [ : : ]accepts step (or stridekwhich defaults to + allows for skipping items and reversing order--see the next section the second-to-last bullet item listed here turns out to be very common techniqueit makes full top-level copy of sequence object--an object with the same valuebut distinct piece of memory (you'll find more on copies in this isn' very useful for immutable objects like stringsbut it comes in handy for objects that may be changed in placesuch as lists in the next you'll see that the syntax used to index by offset (square bracketsis used to index dictionaries by key as wellthe operations look the same but have different interpretations extended slicingthe third limit and slice objects in python and laterslice expressions have support for an optional third indexused as step (sometimes called stridethe step is added to the index of each item extracted the full-blown form of slice is now [ : : ]which means "extract all the items in xfrom offset through - by the third limitkdefaults to + which is why normally all items in slice are extracted from left to right if you specify an explicit valuehoweveryou can use the third limit to skip items or to reverse their order for instancex[ : : will fetch every other item in from offsets - that isit will collect the items at offsets and as usualthe first and second limits default to and the length of the sequencerespectivelyso [:: gets every other item from the beginning to the end of the sequences 'abcdefghijklmnops[ : : 'bdfhjs[:: 'acegikmoskipping items you can also use negative stride to collect items in the opposite order for examplethe slicing expression "hello"[::- returns the new string "olleh"--the first two bounds default to and the length of the sequenceas beforeand stride of - indicates that the slice should go from right to left instead of the usual left to right the effectthereforeis to reverse the sequencestrings in action
779
[::- 'ollehreversing items with negative stridethe meanings of the first two bounds are essentially reversed that isthe slice [ : :- fetches the items from to in reverse order (the result contains items from offsets and ) 'abcedfgs[ : :- 'fdecbounds roles differ skipping and reversing like this are the most common use cases for three-limit slicesbut see python' standard library manual for more details (or run few experiments interactivelywe'll revisit three-limit slices again later in this bookin conjunction with the for loop statement later in the bookwe'll also learn that slicing is equivalent to indexing with slice objecta finding of importance to class writers seeking to support both operations'spam'[ : 'pa'spam'[slice( )'pa'spam'[::- 'maps'spam'[slice(nonenone- )'mapsslicing syntax slice objects with index syntax object why you will careslices throughout this booki will include common use-case sidebars (such as this oneto give you peek at how some of the language features being introduced are typically used in real programs because you won' be able to make much sense of realistic use cases until you've seen more of the python picturethese sidebars necessarily contain many references to topics not introduced yetat mostyou should consider them previews of ways that you may find these abstract language concepts useful for common programming tasks for instanceyou'll see later that the argument words listed on system command line used to launch python program are made available in the argv attribute of the builtin sys modulefile echo py import sys print(sys argvpython echo py - - - ['echo py''- ''- ''- 'usuallyyou're only interested in inspecting the arguments that follow the program name this leads to typical application of slicesa single slice expression can be used to return all but the first item of list heresys argv[ :returns the desired list string fundamentals
780
program name at the front slices are also often used to clean up lines read from input files if you know that line will have an end-of-line character at the end ( \ newline marker)you can get rid of it with single expression such as line[:- ]which extracts all but the last character in the line (the lower limit defaults to in both casesslices do the job of logic that must be explicit in lower-level language having said thatcalling the line rstrip method is often preferred for stripping newline characters because this call leaves the line intact if it has no newline character at the end-- common case for files created with some text-editing tools slicing works if you're sure the line is properly terminated string conversion tools one of python' design mottos is that it refuses the temptation to guess as prime exampleyou cannot add number and string together in pythoneven if the string looks like number ( is all digits)python " typeerrorcan' convert 'intobject to str implicitly python " typeerrorcannot concatenate 'strand 'intobjects this is by designbecause can mean both addition and concatenationthe choice of conversion would be ambiguous insteadpython treats this as an error in pythonmagic is generally omitted if it will make your life more complex what to dothenif your script obtains number as text string from file or user interfacethe trick is that you need to employ conversion tools before you can treat string like numberor vice versa for instanceint(" ")str( ( ' 'repr( ' convert from/to string convert to as-code string the int function converts string to numberand the str function converts number to its string representation (essentiallywhat it looks like when printedthe repr function (and the older backquotes expressionremoved in python xalso converts an object to its string representationbut returns the object as string of code that can be rerun to recreate the object for stringsthe result has quotes around it if displayed with print statementwhich differs in form between python linesprint(str('spam')repr('spam')spam 'spam xprint str('spam')repr('spam'strings in action
781
('spam'"'spam'"raw interactive echo displays see the sidebar in ' "str and repr display formatson page for more on these topics of theseint and str are the generally prescribed to-number and to-string conversion techniques nowalthough you can' mix strings and number types around operators such as +you can manually convert operands before that operation if neededs " typeerrorcan' convert 'intobject to str implicitly int(si force addition str( ' force concatenation similar built-in functions handle floating-point-number conversions to and from stringsstr( )float(" "(' ' text " - float(text - shows more digits before and laterwe'll further study the built-in eval functionit runs string containing python expression code and so can convert string to any kind of object the functions int and float convert only to numbersbut this restriction means they are usually faster (and more securebecause they do not accept arbitrary expression codeas we saw briefly in the string formatting expression also provides way to convert numbers to strings we'll discuss formatting further later in this character code conversions on the subject of conversionsit is also possible to convert single character to its underlying integer code ( its ascii byte valueby passing it to the built-in ord function--this returns the actual binary value used to represent the corresponding character in memory the chr function performs the inverse operationtaking an integer code and converting it to the corresponding characterord(' ' chr( 'stechnicallyboth of these convert characters to and from their unicode ordinals or "code points,which are just their identifying number in the underlying character set string fundamentals
782
the range of code points for other kinds of unicode text may be wider (more on character sets and unicode in you can use loop to apply these functions to all characters in string if required these tools can also be used to perform sort of string-based math to advance to the next characterfor exampleconvert and do the math in integers ' chr(ord( ' chr(ord( ' at least for single-character stringsthis provides an alternative to using the built-in int function to convert from string to integer (though this only makes sense in character sets that order items as your code expects!)int(' ' ord(' 'ord(' ' such conversions can be used in conjunction with looping statementsintroduced in and covered in depth in the next part of this bookto convert string of binary digits to their corresponding integer values each time through the loopmultiply the current value by and add the next digit' integer valueb ' convert binary digits to integer with ord while !'' (ord( [ ]ord(' ') [ : left-shift operation ( < would have the same effect as multiplying by here we'll leave this change as suggested exercisethoughboth because we haven' studied loops in detail yet and because the int and bin built-ins we met in handle binary conversion tasks for us as of python and int(' ' bin( ' convert binary to integerbuilt-in convert integer to binarybuilt-in given enough timepython tends to automate most common tasksstrings in action
783
remember the term "immutable sequence"as we've seenthe immutable part means that you cannot change string in place--for instanceby assigning to an indexs 'spams[ 'xraises an errortypeerror'strobject does not support item assignment how to modify text information in pythonthento change stringyou generally need to build and assign new string using tools such as concatenation and slicingand thenif desiredassign the result back to the string' original names 'spam!to change stringmake new one 'spamspam! [: 'burgers[- 'spamburger!the first example adds substring at the end of sby concatenation reallyit makes new string and assigns it back to sbut you can think of this as "changingthe original string the second example replaces four characters with six by slicingindexingand concatenating as you'll see in the next sectionyou can achieve similar effects with string method calls like replaces 'splots replace('pl''pamal' 'spamalotlike every operation that yields new string valuestring methods generate new string objects if you want to retain those objectsyou can assign them to variable names generating new string object for each string change is not as inefficient as it may sound--rememberas discussed in the preceding python automatically garbage-collects (reclaims the space ofold unused string objects as you goso newer objects reuse the space held by prior values python is usually more efficient than you might expect finallyit' also possible to build up new text values with string formatting expressions both of the following substitute objects into stringin sense converting the objects to strings and changing the original string according to format specification'that is % % bird!( 'dead'that is dead bird'that is { { bird!format( 'dead''that is dead bird!format expressionall pythons format method in despite the substitution metaphorthoughthe result of formatting is new string objectnot modified one we'll study formatting later in this as we'll findformatting turns out to be more general and useful than this example implies because string fundamentals
784
string method calls before we explore formatting further as previewed in and to be covered in python and introduced new string type known as bytearraywhich is mutable and so may be changed in place bytearray objects aren' really text stringsthey're sequences of small -bit integers howeverthey support most of the same operations as normal strings and print as ascii characters when displayed accordinglythey provide another option for large amounts of simple -bit text that must be changed frequently (richer types of unicode text imply different techniquesin we'll also see that ord and chr handle unicode characterstoowhich might not be stored in single bytes string methods in addition to expression operatorsstrings provide set of methods that implement more sophisticated text-processing tasks in pythonexpressions and built-in functions may work across range of typesbut methods are generally specific to object types-string methodsfor examplework only on string objects the method sets of some types intersect in python ( many types have count and copy methods)but they are still more type-specific than other tools method call syntax as introduced in methods are simply functions that are associated with and act upon particular objects technicallythey are attributes attached to objects that happen to reference callable functions which always have an implied subject in finergrained detailfunctions are packages of codeand method calls combine two operations at once--an attribute fetch and callattribute fetches an expression of the form object attribute means "fetch the value of attribute in object call expressions an expression of the form function(argumentsmeans "invoke the code of func tionpassing zero or more comma-separated argument objects to itand return function' result value putting these two together allows us to call method of an object the method call expressionobject method(argumentsstring methods
785
call itpassing in both object and the arguments orin plain wordsthe method call expression means thiscall method to process object with arguments if the method computes resultit will also come back as the result of the entire methodcall expression as more tangible examples 'spamresult find('pa'call the find method to look for 'pain string this mapping holds true for methods of both built-in typesas well as user-defined classes we'll study later as you'll see throughout this part of the bookmost objects have callable methodsand all are accessed using this same method-call syntax to call an object methodas you'll see in the following sectionsyou have to go through an existing objectmethods cannot be run (and make little sensewithout subject methods of strings table - summarizes the methods and call patterns for built-in string objects in python these change frequentlyso be sure to check python' standard library manual for the most up-to-date listor run dir or help call on any string (or the str type nameinteractively python ' string methods vary slightlyit includes decodefor examplebecause of its different handling of unicode data (something we'll discuss in in this tables is string objectand optional arguments are enclosed in square brackets string methods in this table implement higher-level operations such as splitting and joiningcase conversionscontent testsand substring searches and replacements table - string method calls in python capitalize( ljust(width [fill] casefold( lower( center(width [fill] lstrip([chars] count(sub [start [end]] maketrans( [ [ ]] encode([encoding [,errors]] partition(seps endswith(suffix [start [end]] replace(oldnew [count] expandtabs([tabsize] rfind(sub [,start [,end]] find(sub [start [end]] rindex(sub [start [end]] format(fmtstr*args**kwargss rjust(width [fill] index(sub [start [end]] rpartition(seps isalnum( rsplit([sep[maxsplit]] isalpha( rstrip([chars] isdecimal( split([sep [,maxsplit]] string fundamentals
786
splitlines([keepends] isidentifier( startswith(prefix [start [end]] islower( strip([chars] isnumeric( swapcase( isprintable( title( isspace( translate(maps istitle( upper( isupper( zfill(widths join(iterableas you can seethere are quite few string methodsand we don' have space to cover them allsee python' library manual or reference texts for all the fine points to help you get startedthoughlet' work through some code that demonstrates some of the most commonly used methods in actionand illustrates python text-processing basics along the way string method exampleschanging strings ii as we've seenbecause strings are immutablethey cannot be changed in place directly the bytearray supports in-place text changes in and laterbut only for simple -bit types we explored changes to text strings earlierbut let' take quick second look here in the context of string methods in generalto make new text value from an existing stringyou construct new string with operations such as slicing and concatenation for exampleto replace two characters in the middle of stringyou can use code like thiss 'spammys [: 'xxs[ : 'spaxxyslice sections from butif you're really just out to replace substringyou can use the string replace method insteads 'spammys replace('mm''xx' 'spaxxyreplace all mm with xx in the replace method is more general than this code implies it takes as arguments the original substring (of any lengthand the string (of any lengthto replace it withand performs global search and replace'aa$bb$cc$ddreplace('$''spam''aaspambbspamccspamddstring methods
787
in form lettersnotice that this time we simply printed the resultinstead of assigning it to name--you need to assign results to names only if you want to retain them for later use if you need to replace one fixed-size string that can occur at any offsetyou can do replacement againor search for the substring with the string find method and then slices 'xxxxspamxxxxspamxxxxwhere find('spam'search for position where occurs at offset [:where'eggss[(where+ ): 'xxxxeggsxxxxspamxxxxthe find method returns the offset where the substring appears (by defaultsearching from the front)or - if it is not found as we saw earlierit' substring search operation just like the in expressionbut find returns the position of located substring another option is to use replace with third argument to limit it to single substitutions 'xxxxspamxxxxspamxxxxs replace('spam''eggs''xxxxeggsxxxxeggsxxxxs replace('spam''eggs' 'xxxxeggsxxxxspamxxxxreplace all replace one notice that replace returns new string object each time because strings are immutablemethods never really change the subject strings in placeeven if they are called "replace"the fact that concatenation operations and the replace method generate new string objects each time they are run is actually potential downside of using them to change strings if you have to apply many changes to very large stringyou might be able to improve your script' performance by converting the string to an object that does support in-place changess 'spammyl list(sl [' '' '' '' '' '' 'the built-in list function (an object construction callbuilds new list out of the items in any sequence--in this case"explodingthe characters of string into list once the string is in this formyou can make multiple changes to it without generating new copy for each changel[ 'xl[ ' string fundamentals works for listsnot strings
788
[' '' '' '' '' '' 'ifafter your changesyou need to convert back to string ( to write to file)use the string join method to "implodethe list back into strings 'join(ls 'spaxxythe join method may look bit backward at first sight because it is method of strings (not of lists)it is called through the desired delimiter join puts the strings in list (or other iterabletogetherwith the delimiter between list itemsin this caseit uses an empty string delimiter to convert from list back to string more generallyany string delimiter and iterable of strings will do'spamjoin(['eggs''sausage''ham''toast']'eggsspamsausagespamhamspamtoastin factjoining substrings all at once might often run faster than concatenating them individually be sure to also see the earlier note about the mutable bytearray string available as of python and described fully in because it may be changed in placeit offers an alternative to this list/join combination for some kinds of -bit text that must be changed often string method examplesparsing text another common role for string methods is as simple form of text parsing--that isanalyzing structure and extracting substrings to extract substrings at fixed offsetswe can employ slicing techniquesline 'aaa bbb ccccol line[ : col line[ :col 'aaacol 'cccherethe columns of data appear at fixed offsets and so may be sliced out of the original string this technique passes for parsingas long as the components of your data have fixed positions if instead some sort of delimiter separates the datayou can pull out its components by splitting this will work even if the data may show up at arbitrary positions within the stringline 'aaa bbb ccccols line split(cols ['aaa''bbb''ccc'the string split method chops up string into list of substringsaround delimiter string we didn' pass delimiter in the prior exampleso it defaults to whitespace-string methods
789
list of the resulting substrings in other applicationsmore tangible delimiters may separate the data this example splits (and hence parsesthe string at commasa separator common in data returned by some database toolsline 'bob,hacker, line split(','['bob''hacker'' 'delimiters can be longer than single charactertooline " 'mspamaspamlumberjackline split("spam"[" ' "' ''lumberjack'although there are limits to the parsing potential of slicing and splittingboth run very fast and can handle basic text-extraction chores comma-separated text data is part of the csv file formatfor more advanced tools on this frontsee also the csv module in python' standard library other common string methods in action other string methods have more focused roles--for exampleto strip off whitespace at the end of line of textperform case conversionstest contentand test for substring at the end or frontline "the knights who say ni!\nline rstrip('the knights who say ni!line upper('the knights who say ni!\nline isalpha(false line endswith('ni!\ 'true line startswith('the'true alternative techniques can also sometimes be used to achieve the same results as string methods--the in membership operator can be used to test for the presence of substringfor instanceand length and slicing operations can be used to mimic endswithline 'the knights who say ni!\nline find('ni'!- true 'niin line true sub 'ni!\nline endswith(subtrue string fundamentals search via method call or expression end test via method call or slice
790
true see also the format string formatting method described later in this it provides more advanced substitution tools that combine many operations in single step againbecause there are so many methods available for stringswe won' look at every one here you'll see some additional string examples later in this bookbut for more details you can also turn to the python library manual and other documentation sourcesor simply experiment interactively on your own you can also check the help( methodresults for method of any string object for more hintsas we saw in running help on str method likely gives the same details note that none of the string methods accepts patterns--for pattern-based text processingyou must use the python re standard library modulean advanced tool that was introduced in but is mostly outside the scope of this text (one further brief example appears at the end of because of this limitationthoughstring methods may sometimes run more quickly than the re module' tools the original string module' functions (gone in xthe history of python' string methods is somewhat convoluted for roughly the first decade of its existencepython provided standard library module called string that contained functions that largely mirrored the current set of string object methods by popular demandin python these functions were made available as methods of string objects because so many people had written so much code that relied on the original string modulehoweverit was retained for backward compatibility todayyou should use only string methodsnot the original string module in factthe original module call forms of today' string methods have been removed completely from python xand you should not use them in new code in either or howeverbecause you may still see the module in use in older python codeand this text covers both pythons and xa brief look is in order here the upshot of this legacy is that in python xthere technically are still two ways to invoke advanced string operationsby calling object methodsor by calling string module functions and passing in the objects as arguments for instancegiven variable assigned to string objectcalling an object methodx method(argumentsis usually equivalent to calling the same operation through the string module (provided that you have already imported the module)string method(xargumentshere' an example of the method scheme in actions ' + + + replace('+''spam'string methods
791
'aspambspamcspamto access the same operation through the string module in python xyou need to import the module (at least once in your processand pass in the objectimport string string replace( '+''spam' 'aspambspamcspambecause the module approach was the standard for so longand because strings are such central component of most programsyou might see both call patterns in python code you come across againthoughtoday you should always use method calls instead of the older module calls there are good reasons for thisbesides the fact that the module calls have gone away in for one thingthe module call scheme requires you to import the string module (methods do not require importsfor anotherthe module makes calls few characters longer to type (when you load the module with importthat isnot using fromandfinallythe module runs more slowly than methods (the module maps most calls back to the methods and so incurs an extra call along the waythe original string module itselfwithout its string method equivalentsis retained in python because it contains additional toolsincluding predefined string constants ( string digitsand template object system-- relatively obscure formatting tool that predates the string format method and is largely omitted here (for detailssee the brief note comparing it to other formatting tools aheadas well as python' library manualunless you really want to have to change your code to use xthoughyou should consider any basic string operation calls in it to be just ghosts of python past string formatting expressions although you can get lot done with the string methods and sequence operations we've already metpython also provides more advanced way to combine string processing tasks--string formatting allows us to perform multiple type-specific substitutions on string in single step it' never strictly requiredbut it can be convenientespecially when formatting text to be displayed to program' users due to the wealth of new ideas in the python worldstring formatting is available in two flavors in python today (not counting the less-used string module template system mentioned in the prior section)string formatting expressions% (valuesthe original technique available since python' inceptionthis form is based upon the language' "printfmodeland sees widespread use in much existing code string fundamentals
792
newer technique added in python and this form is derived in part from same-named tool in #netand overlaps with string formatting expression functionality since the method call flavor is newerthere is some chance that one or the other of these may become deprecated and removed over time when was released in the expression seemed more likely to be deprecated in later python releases indeed ' documentation threatened deprecation in and removal thereafter this hasn' happened as of and and now looks unlikely given the expression' wide use--in factit still appears even in python' own standard library thousands of times todaynaturallythis story' development depends on the future practice of python' users on the other handbecause both the expression and method are valid to use today and either may appear in code you'll come acrossthis book covers both techniques in full here as you'll seethe two are largely variations on themethough the method has some extra features (such as thousands separators)and the expression is often more concise and seems second nature to most python programmers this book itself uses both techniques in later examples for illustrative purposes if its author has preferencehe will keep it largely classifiedexcept to quote from python' import this mottothere should be one--and preferably only one--obvious way to do it unless the newer string formatting method is compellingly better than the original and widely used expressionits doubling of python programmersknowledge base requirements in this domain seems unwarranted--and even un-pythonicper the original and longstanding meaning of that term programmers should not have to learn two complicated tools if those tools largely overlap you'll have to judge for yourself whether formatting merits the added language heftof courseso let' give both fair hearing formatting expression basics since string formatting expressions are the original in this departmentwe'll start with them python defines the binary operator to work on strings (you may recall that this is also the remainder of divisionor modulusoperator for numberswhen applied to stringsthe operator provides simple way to format values as strings according to format definition in shortthe operator provides compact way to code multiple string substitutions all at onceinstead of building and concatenating parts individually to format strings on the left of the operatorprovide format string containing one or more embedded conversion targetseach of which starts with ( %dstring formatting expressions
793
on the right of the operatorprovide the object (or objectsembedded in tuplethat you want python to insert into the format string on the left in place of the conversion target (or targetsfor instancein the formatting example we saw earlier in this the integer replaces the % in the format string on the leftand the string 'deadreplaces the % the result is new string that reflects these two substitutionswhich may be printed or saved for use in other roles'that is % % bird!( 'dead'that is dead birdformat expression technically speakingstring formatting expressions are usually optional--you can generally do similar work with multiple concatenations and conversions howeverformatting allows us to combine many steps into single operation it' powerful enough to warrant few more examplesexclamation 'ni'the knights who say % !exclamation 'the knights who say ni!string substitution '% % % you( 'spam' ' spam youtype-specific substitutions '% -% -% ( [ ]' - -[ ]all types match % target the first example here plugs the string 'niinto the target on the leftreplacing the % marker in the second examplethree values are inserted into the target string note that when you're inserting more than one valueyou need to group the values on the right in parentheses ( put them in tuplethe formatting expression operator expects either single item or tuple of one or more items on its right side the third example again inserts three values--an integera floating-point objectand list object--but notice that all of the targets on the left are %swhich stands for conversion to string as every type of object can be converted to string (the one used when printing)every object type works with the % conversion code because of thisunless you will be doing some special formatting% is often the only code you need to remember for the formatting expression againkeep in mind that formatting always makes new stringrather than changing the string on the leftbecause strings are immutableit must work this way as beforeassign the result to variable name if you need to retain it advanced formatting expression syntax for more advanced type-specific formattingyou can use any of the conversion type codes listed in table - in formatting expressionsthey appear after the character in substitution targets programmers will recognize most of these because python string formatting supports all the usual printf format codes (but returns the resultinstead string fundamentals
794
ways to format the same typefor instance% %fand % provide alternative ways to format floating-point numbers table - string formatting type codes code meaning string (or any object' str(xstringr same as sbut uses reprnot str character (int or strd decimal (base- integeri integer same as (obsoleteno longer unsignedo octal integer (base hex integer (base same as xbut with uppercase letters floating point with exponentlowercase same as ebut uses uppercase letters floating-point decimal same as fbut uses uppercase letters floating-point or floating-point or literal (coded as %%in factconversion targets in the format string on the expression' left side support variety of conversion operations with fairly sophisticated syntax all their own the general structure of conversion targets looks like this%[(keyname)][flags][width]precision]typecode the type code characters in the first column of table - show up at the end of this target string' format between the and the type code characteryou can do any of the followingprovide key name for indexing the dictionary used on the right side of the expression list flags that specify things like left justification (-)numeric sign (+) blank before positive numbers and for negatives ( space)and zero fills ( give total minimum field width for the substituted text set the number of digits (precisionto display after decimal point for floatingpoint numbers string formatting expressions
795
take their values from the next item in the input values on the expression' right side (useful when this isn' known until runtimeand if you don' need any of these extra toolsa simple % in the format string will be replaced by the corresponding value' default print stringregardless of its type advanced formatting expression examples formatting target syntax is documented in full in the python standard manuals and reference textsbut to demonstrate common usagelet' look at few examples this one formats integers by defaultand then in six-character field with left justification and zero paddingx res 'integers% %- % (xxxres 'integers the % %fand % formats display floating-point numbers in different waysas the following interaction demonstrates--% is the same as % but the exponent is uppercaseand chooses formats by number content (it' formally defined to use exponential format if the exponent is less than - or not less than precisionand decimal format otherwisewith default total digits precision of ) shows more digits before and '% % % (xxx' + '%ex ' + for floating-point numbersyou can achieve variety of additional formatting effects by specifying left justificationzero paddingnumeric signstotal field widthand digits after the decimal point for simpler tasksyou might get by with simply converting to strings with % format expression or the str built-in function shown earlier'%- % %+ (xxx' + '%sxstr( (' '' 'when sizes are not known until runtimeyou can use computed width and precision by specifying them with in the format string to force their values to be taken from the next item in the inputs to the right of the operator--the in the tuple here gives precision'% * ( ' string fundamentals
796
dictionary-based formatting expressions as more advanced extensionstring formatting also allows conversion targets on the left to refer to the keys in dictionary coded on the right and fetch the corresponding values this opens the door to using formatting as sort of template tool we've only met dictionaries briefly thus far in but here' an example that demonstrates the basics'%(qty) more %(food) {'qty' 'food''spam'' more spamherethe (qtyand (foodin the format string on the left refer to keys in the dictionary literal on the right and fetch their associated values programs that generate text such as html or xml often use this technique--you can build up dictionary of values and substitute them all at once with single formatting expression that uses key-based references (notice the first comment is above the triple quote so it' not added to the stringand ' typing this in idle without prompt for continuation lines)reply ""greetings hello %(name)syour age is %(age) ""values {'name''bob''age' print(reply valuestemplate with substitution targets build up values to substitute perform substitutions greetings hello bobyour age is this trick is also used in conjunction with the vars built-in functionwhich returns dictionary containing all the variables that exist in the place it is calledfood 'spamqty vars({'food''spam''qty' plus built-in names set by python when used on the right side of format operationthis allows the format string to refer to variables by name--as dictionary keys'%(qty) more %(food)svars(' more spamvariables are keys in vars(we'll study dictionaries in more depth in see also for examples that convert to hexadecimal and octal number strings with the % and % formatting expression target codeswhich we won' repeat here additional formatting expression string formatting expressions
797
next and final string topic string formatting method calls as mentioned earlierpython and introduced new way to format strings that is seen by some as bit more python-specific unlike formatting expressionsformatting method calls are not closely based upon the language' "printfmodeland are sometimes more explicit in intent on the other handthe new technique still relies on core "printfconceptssuch as type codes and formatting specifications moreoverit largely overlaps with--and sometimes requires bit more code than--formatting expressionsand in practice can be just as complex in many roles because of thisthere is no best-use recommendation between expressions and method calls todayand most programmers would be well served by cursory understanding of both schemes luckilythe two are similar enough that many core concepts overlap formatting method basics the string object' format methodavailable in python and xis based on normal function call syntaxinstead of an expression specificallyit uses the subject string as templateand takes any number of arguments that represent values to be substituted according to the template its use requires knowledge of functions and callsbut is mostly straightforward within the subject stringcurly braces designate substitution targets and arguments to be inserted either by position ( { })or keyword ( {food})or relative position in and later ({}as we'll learn when we study argument passing in depth in arguments to functions and methods may be passed by position or keyword nameand python' ability to collect arbitrarily many positional and keyword arguments allows for such general method call patterns for exampletemplate '{ }{ and { }template format('spam''ham''eggs''spamham and eggsby position template '{motto}{porkand {food}template format(motto='spam'pork='ham'food='eggs''spamham and eggsby keyword template '{motto}{ and {food}template format('ham'motto='spam'food='eggs''spamham and eggsby both template '{}{and {}template format('spam''ham''eggs''spamham and eggsby relative position new in and string fundamentals
798
uses dictionaries instead of keyword argumentsand doesn' allow quite as much flexibility for value sources (which may be an asset or liabilitydepending on your perspective)more on how the two techniques compare aheadsame via expression template '% % and %stemplate ('spam''ham''eggs''spamham and eggstemplate '%(motto) %(pork) and %(food)stemplate dict(motto='spam'pork='ham'food='eggs''spamham and eggsnote the use of dict(to make dictionary from keyword arguments hereintroduced in and covered in full in it' an often less-cluttered alternative to the literal naturallythe subject string in the format method call can also be literal that creates temporary stringand arbitrary object types can be substituted at targets much like the expression' % code'{motto}{ and {food}format( motto= food=[ ]' and [ ]just as with the expression and other string methodsformat creates and returns new string objectwhich can be printed immediately or saved for further work (recall that strings are immutableso format really must make new objectstring formatting is not just for displayx '{motto}{ and {food}format( motto= food=[ ] ' and [ ] split(and '[' ''[ ]' replace('and''but under no circumstances' ' but under no circumstances [ ]adding keysattributesand offsets like formatting expressionsformat calls can become more complex to support more advanced usage for instanceformat strings can name object attributes and dictionary keys--as in normal python syntaxsquare brackets name dictionary keys and dots denote object attributes of an item referenced by position or keyword the first of the following examples indexes dictionary on the key "spamand then fetches the attribute "platformfrom the already imported sys module object the second does the samebut names the objects by keyword instead of positionimport sys 'my { [kind]runs { platform}format(sys{'kind''laptop'}'my laptop runs win string formatting method calls
799
'my laptop runs win square brackets in format strings can name list (and other sequenceoffsets to perform indexingtoobut only single positive offsets work syntactically within format stringsso this feature is not as general as you might think as with expressionsto name negative offsets or slicesor to use arbitrary expression results in generalyou must run expressions outside the format string itself (note the use of *parts here to unpack tuple' items into individual function argumentsas we did in when studying fractionsmore on this form in )somelist list('spam'somelist [' '' '' '' ''first={ [ ]}third={ [ ]}format(somelist'first=sthird= 'first={ }last={ }format(somelist[ ]somelist[- ]'first=slast= [- fails in fmt parts somelist[ ]somelist[- ]somelist[ : 'first={ }last={ }middle={ }format(*parts"first=slast=mmiddle=[' '' '][ : fails in fmt or '{}in advanced formatting method syntax another similarity with expressions is that you can achieve more specific layouts by adding extra syntax in the format string for the formatting methodwe use colon after the possibly empty substitution target' identificationfollowed by format specifier that can name the field sizejustificationand specific type code here' the formal structure of what can appear as substitution target in format string--its four parts are all optionaland must appear without intervening spaces{fieldname component !conversionflag :formatspecin this substitution target syntaxfieldname is an optional number or keyword identifying an argumentwhich may be omitted to use relative argument numbering in and later component is string of zero or more nameor "[index]references used to fetch attributes and indexed values of the argumentwhich may be omitted to use the whole argument value conversionflag starts with if presentwhich is followed by rsor to call reprstror ascii built-in functions on the valuerespectively formatspec starts with if presentwhich is followed by text that specifies how the value should be presentedincluding details such as field widthalignmentpaddingdecimal precisionand so onand ends with an optional data type code string fundamentals