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 (b...
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...
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 de...
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([...
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 o...
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 ear...
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 ...
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 sup...
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 indexi...
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 f...
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 an...
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 ...
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...
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 (iterabless...
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 s...
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 prec...
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 compl...
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 fur...
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 ty...
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 a...
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 th...
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 interestingly...
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( tr...
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 remaindersotherwis...
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 s...
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 truncregardle...
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 ...
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...
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 deci...
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'...
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 othe...
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...
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 strin...
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 ...
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 py...
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 d...
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 ma...
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 st...
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 objec...
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 ...
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 va...
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...
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...
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 creat...
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 modulestyp...
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 ...
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...
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 r...
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 truth...
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 usu...
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 th...
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 certa...
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...
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)py...
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 ...
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 ...
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 referen...
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 st...
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 passin...
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 mu...
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 o...
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 pas...
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 ga...
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 t...
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...
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 ...
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 ...
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 ...
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 ei...
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 s...
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 ...
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 va...
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 qu...
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...
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...
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 pyt...
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 stringan...
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 ...
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 la...
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 ...
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 default...
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 conv...
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 m...
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 ...
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 o...
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 l...
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 manua...
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 st...
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...
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 "...
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 f...
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 compone...
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 expressi...
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...
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 octa...
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 expres...
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 thu...
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 int...
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) %...
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 expr...