id
int64
0
25.6k
text
stringlengths
0
4.59k
8,600
rapid introduction to procedural programming numbers[ count sum lowest highest mean it will take about four lines to initialize the necessary variables (an empty list is simply [])and less than lines for the while loopincluding basic error handling printing out at the end can be done in just few linesso the whole programincluding blank lines for the sake of clarityshould be about lines in some situations we need to generate test text--for exampleto populate web site design before the real content is availableor to provide test content when developing report writer to this endwrite program that generates awful poems (the kind that would make vogon blushrandom randint(and random choice( create some lists of wordsfor examplearticles ("the"" "etc )subjects ("cat""dog""man""woman")verbs ("sang""ran""jumped")and adverbs ("loudly""quietly""well""badly"then loop five timesand on each iteration use the random choice(function to pick an articlesubjectverband adverb use random randint(to choose between two sentence structuresarticlesubjectverband adverbor just articlesubjectand verband print the sentence here is an example runawfulpoetry _ans py another boy laughed badly the woman jumped boy hoped horse jumped another man laughed rudely you will need to import the random module the lists can be done in about - lines depending on how many words you put in themand the loop itself requires less than ten linesso with some blank lines the whole program can be done in about lines of code solution is provided as awfulpoetry _ans py to make the awful poetry program more versatileadd some code to it so that if the user enters number on the command line (between and inclusive)the program will output that many lines if no command-line argument is givendefault to printing five lines as before you'll need to change the main loop ( to while loopkeep in mind that python' comparison operators can be chainedso there' no need to use logical and when checking that the argument is in range the additional functionality can be done by adding about ten lines of code solution is provided as awfulpoetry _ans py it would be nice to be able to calculate the median (middle valueas well as the mean for the averages program in exercise but to do this we must sort the list in python list can easily be sorted using the list sort(
8,601
methodbut we haven' covered that yetso we won' use it here extend the averages program with block of code that sorts the list of numbers--efficiency is of no concernjust use the easiest approach you can think of once the list is sortedthe median is the middle value if the list has an odd number of itemsor the average of the two middle values if the list has an even number of items calculate the median and output that along with the other information this is rather trickyespecially for inexperienced programmers if you have some python experienceyou might still find it challengingat least if you keep to the constraint of using only the python we have covered so far the sorting can be done in about dozen lines and the median calculation (where you can' use the modulus operatorsince it hasn' been covered yetin four lines solution is provided in average _ans py
8,602
identifiers and keywords integral types floating-point types strings |||data types in this we begin to take much more detailed look at the python language we start with discussion of the rules governing the names we give to object referencesand provide list of python' keywords then we look at all of python' most important data types--excluding collection data typeswhich are covered in the data types considered are all built-inexcept for one which comes from the standard library the only difference between builtin data types and library data types is that in the latter casewe must first import the relevant module and we must qualify the data type' name with the name of the module it comes from-covers importing in depth identifiers and keywords object references ||when we create data item we can either assign it to variableor insert it into collection (as we noted in the preceding when we assign in pythonwhat really happens is that we bind an object reference to refer to the object in memory that holds the data the names we give to our object references are called identifiers or just plain names valid python identifier is nonempty sequence of characters of any length that consists of "start characterand zero or more "continuation characterssuch an identifier must obey couple of rules and ought to follow certain conventions the first rule concerns the start and continuation characters the start character can be anything that unicode considers to be letterincluding the ascii letters (" "" "" "" "" "" ")the underscore (" ")as well as the letters from most non-english languages each continuation character can be any character that is permitted as start characteror pretty well any nonwhitespace characterincluding any character that unicode considers to be digitsuch as (" "" "" ")or the catalan character "*identifiers are case
8,603
data types sensitiveso for exampletaxratetaxratetaxratetaxrateand taxrate are five different identifiers the precise set of characters that are permitted for the start and continuation are described in the documentation (python language referencelexical analysisidentifiers and keywords section)and in pep (supporting non-ascii identifiersthe second rule is that no identifier can have the same name as one of python' keywordsso we cannot use any of the names shown in table table python' keywords and continue except global lambda pass while as def false if none raise with assert del finally import nonlocal return yield break elif for in not true class else from is or try we already met most of these keywords in the preceding although of them--assertclassdelfinallyfromgloballambdanonlocalraisewithand yield--have yet to be discussed the first convention isdon' use the names of any of python' predefined identifiers for your own identifiers soavoid using notimplemented and ellipsisand the name of any of python' built-in data types (such as intfloatliststrand tuple)and any of python' built-in functions or exceptions how can we tell whether an identifier falls into one of these categoriespython has built-in function called dir(that returns list of an object' attributes if it is called with no arguments it returns the list of python' built-in attributes for exampledir(python ' list has an extra item'__package__['__builtins__''__doc__''__name__'the __builtins__ attribute isin effecta module that holds all of python' built-in attributes we can use it as an argument to the dir(functiondir(__builtins__['arithmeticerror''assertionerror''attributeerror''sum''super''tuple''type''vars''zip' "pepis python enhancement proposal if someone wants to change or extend pythonproviding they get enough support from the python communitythey submit pep with the details of their proposal so that it can be formally consideredand in some cases such as with pep accepted and implemented all the peps are accessible from www python org/dev/peps
8,604
there are about names in the listso we have omitted most of them those that begin with capital letter are the names of python' built-in exceptionsthe rest are function and data type names the second convention concerns the use of underscores (_names that begin and end with two underscores (such as __lt__should not be used python defines various special methods and variables that use such names (and in the case of special methodswe can reimplement themthat ismake our own versions of them)but we should not introduce new names of this kind ourselves we will cover such names in names that begin with one or two leading underscores (and that don' end with two underscoresare treated specially in some contexts we will show when to use names with single leading underscore in and when to use those with two leading underscores in single underscore on its own can be used as an identifierand inside an interactive interpreter or python shell_ holds the result of the last expression that was evaluated in normal running program no existsunless we use it explicitly in our code some programmers like to use in for in loops when they don' care about the items being looped over for examplefor in ( )print("hello"import be awarehoweverthat those who write programs that are internationalized often use as the name of their translation function they do this so that instead of writing gettext gettext("translate me")they can write ("translate me"(for this code to work we must have first imported the gettext module so that we can access the module' gettext(function let' look at some valid identifiers in snippet of code written by spanishspeaking programmer the code assumes we have done import math and that the variables radio and vieja_area have been created earlier in the programp math pi nueva_area radio radio if abs(nueva_area vieja_areaeprint("las areas han convergido"we've used the math moduleset epsilon (eto be very small floating-point numberand used the abs(function to get the absolute value of the difference between the areas--we cover all of these later in this what we are concerned with here is that we are free to use accented characters and greek letters for identifiers we could just as easily create identifiers using arabicchinesehebrewjapaneseand russian charactersor indeed characters from any other language supported by the unicode character set import
8,605
data types the easiest way to check whether something is valid identifier is to try to assign to it in an interactive python interpreter or in idle' python shell window here are some examplesstretch-factor syntaxerrorcan' assign to operator miles syntaxerrorinvalid syntax str legal but bad 'impot syntaxerroreol while scanning single-quoted string l_impot when an invalid identifier is used it causes syntaxerror exception to be raised in each case the part of the error message that appears in parentheses variesso we have replaced it with an ellipsis the first assignment fails because "-is not unicode letterdigitor underscore the second one fails because the start character is not unicode letter or underscoreonly continuation characters can be digits no exception is raised if we create an identifier that is valid--even if the identifier is the name of built-in data typeexceptionor function--so the third assignment worksalthough it is ill-advised the fourth fails because quote is not unicode letterdigitor underscore the fifth is fine integral types ||python provides two built-in integral typesint and bool both integers and booleans are immutablebut thanks to python' augmented assignment operators this is rarely noticeable when used in boolean expressions and false are falseand any other integer and true are true when used in numerical expressions true evaluates to and false to this means that we can write some rather odd things--for examplewe can increment an integeriusing the expression +true naturallythe correct way to do this is + integers |the size of an integer is limited only by the machine' memoryso integers hundreds of digits long can easily be created and worked with--although they will be slower to use than integers that can be represented natively by the machine' processor the standard library also provides the fractions fraction type (unlimited precision rationalswhich may be useful in some specialized mathematical and scientific contexts dealing with syntax errors
8,606
table numeric operators and functions tuples syntax description adds number and number subtracts from multiplies by divides by yalways produces float (or complex if or is complexx / divides by ytruncates any fractional part so always produces an int resultsee also the round(function produces the modulus (remainderof dividing by * raises to the power of ysee also the pow(functions - negates xchanges ' sign if nonzerodoes nothing if zero + does nothingis sometimes used to clarify code abs(xreturns the absolute value of divmod(xyreturns the quotient and remainder of dividing by as tuple of two ints pow(xyraises to the power of ythe same as the *operator pow(xyza faster alternative to ( *yz round(xnreturns rounded to integral digits if is negative int or returns rounded to decimal places if is positive intthe returned value has the same type as xsee the text table integer conversion functions syntax description bin(ireturns the binary representation of int as stringe bin( =' hex(ireturns the hexadecimal representation of as stringe hex( =' bcint(xconverts object to an integerraises valueerror on failure--or typeerror if ' data type does not support integer conversion if is floating-point number it is truncated int(sbaseconverts str to an integerraises valueerror on failure if the optional base argument is given it should be an integer between and inclusive returns the octal representation of as stringe oct(ioct( =' tuples
8,607
data types integer literals are written using base (decimalby defaultbut other number bases can be used when this is convenient xdecade decimal binary octal hexadecimal binary numbers are written with leading boctal numbers with leading oand hexadecimal numbers with leading uppercase letters can also be used all the usual mathematical functions and operators can be used with integersas table shows some of the functionality is provided by built-in functions like abs()--for exampleabs(ireturns the absolute value of integer --and other functionality is provided by int operators--for examplei returns the sum of integers and we will mention just one of the functions from table since all the others are sufficiently explained in the table itself while for floatsthe round(function works in the expected way--for exampleround( produces --for intsusing positive rounding value has no effect and results in the same number being returnedsince there are no decimal digits to work on but when negative rounding value is used subtle and useful behavior is achieved--for exampleround( - produces and round( - produces all the binary numeric operators (+-///%and **have augmented assignment versions (+=-=/=//=%=and **=where opy is logically equivalent to op in the normal case when reading ' value has no side effects objects can be created by assigning literals to variablesfor examplex or by calling the relevant data type as functionfor examplex int( some objects ( those of type decimal decimalcan be created only by using the data type since they have no literal representation when an object is created using its data type there are three possible use cases the first use case is when data type is called with no arguments in this case an object with default value is created--for examplex int(creates an integer of value all the built-in types can be called with no arguments the second use case is when the data type is called with single argument if an argument of the same type is givena new object which is shallow copy of users of -style languages note that single leading is not sufficient to specify an octal number (zeroletter omust be used in python
8,608
the original object is created (shallow copying is covered in if an argument of different type is givena conversion is attempted this use is shown for the int type in table if the argument is of type that supports conversions to the given type and the conversion failsa valueerror exception is raisedotherwisethe resultant object of the given type is returned if the argument' data type does not support conversion to the given type typeerror exception is raised the built-in float and str types both provide integer conversionsit is also possible to provide integer and other conversions for our own custom data types as we will see in copying collections type conversions the third use case is where two or more arguments are given--not all types support thisand for those that do the argument types and their meanings vary for the int type two arguments are permitted where the first is string that represents an integer and the second is the number base of the string representation for exampleint(" " creates an integer of value this use is shown in table the bitwise operators are shown in table all the binary bitwise operators (|^&>have augmented assignment versions (|=^=&=<<=and >>=where opj is logically equivalent to op in the normal case when reading ' value has no side effects from python the int bit_length(method is available this returns the number of bits required to represent the int it is called on for example( bit_length(returns (the parentheses are required if literal integer is usedbut not if we use an integer variable if many true/false flags need to be heldone possibility is to use single integerand to test individual bits using the bitwise operators the same thing can be achieved less compactlybut more convenientlyusing list of booleans table integer bitwise operators syntax description bitwise or of int and int jnegative numbers are assumed to be represented using ' complement bitwise xor (exclusive orof and bitwise and of and < shifts left by bitslike ( *jwithout overflow checking > shifts right by bitslike /( *jwithout overflow checking ~ inverts ' bits
8,609
data types booleans |there are two built-in boolean objectstrue and false like all other python data types (whether built-inlibraryor custom)the bool data type can be called as function--with no arguments it returns falsewith bool argument it returns copy of the argumentand with any other argument it attempts to convert the given object to bool all the built-in and standard library data types can be converted to produce boolean valueand it is easy to provide boolean conversions for custom data types here are couple of boolean assignments and couple of boolean expressionst true false and false and true true logical operators as we noted earlierpython provides three logical operatorsandorand not both and and or use short-circuit logic and return the operand that determined the resultwhereas not always returns either true or false programmers who have been using older versions of python sometimes use and instead of true and falsethis almost always works finebut new code should use the built-in boolean objects when boolean value is required floating-point types ||python provides three kinds of floating-point valuesthe built-in float and complex typesand the decimal decimal type from the standard library all three are immutable type float holds double-precision floating-point numbers whose range depends on the (or cor javacompiler python was built withthey have limited precision and cannot reliably be compared for equality numbers of type float are written with decimal pointor using exponential notationfor example - - - computers natively represent floating-point numbers using base --this means that some decimals can be represented exactly (such as )but others only approximately (such as and furthermorethe representation uses fixed number of bitsso there is limit to the number of digits that can be held here is salutary example typed into idle - - ( -
8,610
the inexactness is not problem specific to python--all programming languages have this problem with floating-point numbers python produces much more sensible-looking output - - ( - when python outputs floating-point numberin most cases it uses david gay' algorithm this outputs the fewest possible digits without losing any accuracy although this produces nicer outputit doesn' change the fact that computers (no matter what computer language is usedeffectively store floating-point numbers as approximations if we need really high precision there are two approaches we can take one approach is to use ints--for exampleworking in terms of pennies or tenths of penny or similar--and scale the numbers when necessary this requires us to be quite carefulespecially when dividing or taking percentages the other approach is to use python' decimal decimal numbers from the decimal module these perform calculations that are accurate to the level of precision we specify (by defaultto decimal placesand can represent periodic numbers like exactlybut processing is lot slower than with floats because of their accuracydecimal decimal numbers are suitable for financial calculations mixed mode arithmetic is supported such that using an int and float produces floatand using float and complex produces complex because decimal decimals are of fixed precision they can be used only with other decimal decimals and with intsin the latter case producing decimal decimal result if an operation is attempted using incompatible typesa typeerror exception is raised floating-point numbers |all the numeric operators and functions in table ( can be used with floatsincluding the augmented assignment versions the float data type can be called as function--with no arguments it returns with float argument it returns copy of the argumentand with any other argument it attempts to convert the given object to float when used for conversions string argument can be giveneither using simple decimal notation or using exponential notation it is possible that nan ("not number"or "infinitymay be produced by calculation involving floats--unfortunately the behavior is not consistent across implementations and may differ depending on the system' underlying math library here is simple function for comparing floats for equality to the limit of the machine' accuracy
8,611
data types table the math module' functions and constants # tuples syntax description math acos(xreturns the arc cosine of in radians math acosh(xreturns the arc hyperbolic cosine of in radians math asin(xreturns the arc sine of in radians math asinh(xreturns the arc hyperbolic sine of in radians math atan(xreturns the arc tangent of in radians math atan (yxreturns the arc tangent of in radians math atanh(xreturns the arc hyperbolic tangent of in radians math ceil(xreturns the smallest integer greater than or equal to as an inte math ceil( = math copysign( ,yreturns with ' sign math cos(xreturns the cosine of in radians math cosh(xreturns the hyperbolic cosine of in radians math degrees(rconverts float from radians to degrees math the constant eapproximately math exp(xreturns exi math * math fabs(xreturns | the absolute value of as float math factorial(xreturns xmath floor(xreturns the largest integer less than or equal to as an inte math floor( = math fmod(xyproduces the modulus (remainderof dividing by ythis produces better results than for floats math frexp(xreturns -tuple with the mantissa (as floatand the exponent (as an intsox see math ldexp(math fsum(ireturns the sum of the values in iterable as float math hypot(xyreturns math isinf(xreturns true if float is +inf +math isnan(xreturns true if float is nan ("not number"math ldexp(mereturns effectively the inverse of math frexp(math log(xbreturns logb xb is optional and defaults to math math log (xreturns log math log (xreturns loge( )accurate even when is close to math modf(xreturns ' fractional and whole parts as two floats tuples
8,612
table the math module' functions and constants # syntax description math pi the constant papproximately math pow(xyreturns xy as float math radians(dconverts float from degrees to radians math sin(xreturns the sine of in radians math sinh(xreturns the hyperbolic sine of in radians math sqrt(xreturns math tan(xreturns the tangent of in radians math tanh(xreturns the hyperbolic tangent of in radians math trunc(xreturns the whole part of as an intsame as int(xdef equal_float(ab)return abs( <sys float_info epsilon this requires us to import the sys module the sys float_info object has many attributessys float_info epsilon is effectively the smallest difference that the machine can distinguish between two floating-point numbers on one of the author' -bit machines it is just over (epsilon is the traditional name for this number python floats normally provide reliable accuracy for up to significant digits if you type sys float_info into idleall its attributes will be displayedthese include the minimum and maximum floating-point numbers the machine can represent and typing help(sys float_infowill print some information about the sys float_info object floating-point numbers can be converted to integers using the int(function which returns the whole part and throws away the fractional partor using round(which accounts for the fractional partor using math floor(or math ceil(which convert down to or up to the nearest integer the float is_integer(method returns true if floating-point number' fractional part is and float' fractional representation can be obtained using the float as_integer_ratio(method for examplegiven the call as_integer_ratio(returns ( integers can be converted to floatingpoint numbers using float(floating-point numbers can also be represented as strings in hexadecimal format using the float hex(method such strings can be converted back to floating-point numbers using the float fromhex(method for examples hex(str =' +
8,613
data types float fromhex(st hex(float = str =' + the exponent is indicated using ("power"rather than since is valid hexadecimal digit in addition to the built-in floating-point functionalitythe math module provides many more functions that operate on floatsas shown in tables and here are some code snippets that show how to make use of the module' functionalityimport math math pi ( * python outputs math hypot( math modf( python outputs( ( the math hypot(function calculates the distance from the origin to the point (xyand produces the same result as math sqrt(( * ( * )the math module is very dependent on the underlying math library that python was compiled against this means that some error conditions and boundary cases may behave differently on different platforms complex numbers |the complex data type is an immutable type that holds pair of floatsone representing the real part and the other the imaginary part of complex number literal complex numbers are written with the real and imaginary parts joined by or signand with the imaginary part followed by here are some examples + + - notice that if the real part is we can omit it entirely the separate parts of complex are available as attributes real and imag for examplez - + realz imag (- except for //%divmod()and the three-argument pow()all the numeric operators and functions in table ( can be used with complex numbersand so can the augmented assignment versions in additioncomplex numbers mathematicians use to signify but python follows the engineering tradition and uses
8,614
have methodconjugate()which changes the sign of the imaginary part for examplez conjugate(( - conjugate(( + jnotice that here we have called method on literal complex number in generalpython allows us to call methods or access attributes on any literalas long as the literal' data type provides the called method or the attribute--howeverthis does not apply to special methodssince these always have corresponding operators such as that should be used instead for example real produces imag produces and + produces + the complex data type can be called as function--with no arguments it returns jwith complex argument it returns copy of the argumentand with any other argument it attempts to convert the given object to complex when used for conversions complex(accepts either single string argumentor one or two floats if just one float is giventhe imaginary part is taken to be the functions in the math module do not work with complex numbers this is deliberate design decision that ensures that users of the math module get exceptions rather than silently getting complex numbers in some situations users of complex numbers can import the cmath modulewhich provides complex number versions of most of the trigonometric and logarithmic functions that are in the math moduleplus some complex number-specific functions such as cmath phase()cmath polar()and cmath rect()and also the cmath pi and cmath constants which hold the same float values as their math module counterparts decimal numbers |in many applications the numerical inaccuracies that can occur when using floats don' matterand in any case are far outweighed by the speed of calculation that floats offer but in some cases we prefer the opposite trade-offand want complete accuracyeven at the cost of speed the decimal module provides immutable decimal numbers that are as accurate as we specify calculations involving decimals are slower than those involving floatsbut whether this is noticeable will depend on the application to create decimal we must import the decimal module for exampleimport decimal decimal decimal(
8,615
data types decimal decimal(" " decimal(' 'decimal numbers are created using the decimal decimal(function this function can take an integer or string argument--but not floatsince floats are held inexactly whereas decimals are represented exactly if string is used it can use simple decimal notation or exponential notation in addition to providing accuracythe exact representation of decimal decimals means that they can be reliably compared for equality from python it is possible to convert floats to decimals using the decimal decimal from_float(function this function takes float as argument and returns the decimal decimal that is closest to the number the float approximates all the numeric operators and functions listed in table ( )including the augmented assignment versionscan be used with decimal decimalsbut with couple of caveats if the *operator has decimal decimal left-hand operandits right-hand operand must be an integer similarlyif the pow(function' first argument is decimal decimalthen its second and optional third arguments must be integers the math and cmath modules are not suitable for use with decimal decimalsbut some of the functions provided by the math module are provided as decimal decimal methods for exampleto calculate ex where is floatwe write math exp( )but where is decimal decimalwe write exp(from the discussion in piece # ( )we can see that exp(isin effectsyntactic sugar for decimal decimal exp(xthe decimal decimal data type also provides ln(which calculates the natural (base elogarithm (just like math log(with one argument)log ()and sqrt()along with many other methods specific to the decimal decimal data type numbers of type decimal decimal work within the scope of contextthe context is collection of settings that affect how decimal decimals behave the context specifies the precision that should be used (the default is decimal places)the rounding techniqueand some other details in some situations the difference in accuracy between floats and decimal decimals becomes obvious print( print(decimal decimal( decimal decimal(" ")
8,616
decimal decimal( decimal decimal(" "decimal(' 'although the division using decimal decimals is more accurate than the one involving floatsin this case (on -bit machinethe difference only shows up in the fifteenth decimal place in many situations this is insignificant--for examplein this bookall the examples that need floating-point numbers use floats one other point to note is that the last two of the preceding examples reveal for the first time that printing an object involves some behind-the-scenes formatting when we call print(on the result of decimal decimal( decimal decimal(" "the bare number is printed--this output is in string form if we simply enter the expression we get decimal decimal output--this output is in representational form all python objects have two output forms string form is designed to be human-readable representational form is designed to produce output that if fed to python interpreter would (when possiblereproduce the represented object we will return to this topic in the next section where we discuss stringsand again in when we discuss providing string and representational forms for our own custom data types the library reference' decimal module documentation provides all the details that are too obscure or beyond our scope to coverit also provides more examplesand faq list strings ||strings are represented by the immutable str data type which holds sequence of unicode characters the str data type can be called as function to create string objects--with no arguments it returns an empty stringwith nonstring argument it returns the string form of the argumentand with string argument it returns copy of the string the str(function can also be used as conversion functionin which case the first argument should be string or something convertable to stringwith up to two optional string arguments being passedone specifying the encoding to use and the other specifying how to handle encoding errors earlier we mentioned that string literals are created using quotesand that we are free to use single or double quotes providing we use the same at both ends in additionwe can use triple quoted string--this is python-speak for string that begins and ends with three quote characters (either three single quotes or three double quotesfor exampletext """ triple quoted string like this can include 'quotesand "quoteswithout formality we can also escape newlines so this particular string is actually only two lines long ""character encodings
8,617
data types table python' string escapes escape meaning \newline escape ( ignorethe newline \backslash (\\single quote ('\double quote ("\ ascii bell (bel\ ascii backspace (bs\ ascii formfeed (ff\ ascii linefeed (lf\ {nameunicode character with the given name \ooo character with the given octal value \ ascii carriage return (cr\ ascii tab (tab\uhhhh unicode character with the given -bit hexadecimal value \uhhhhhhhh unicode character with the given -bit hexadecimal value \ ascii vertical tab (vt\xhh character with the given -bit hexadecimal value if we want to use quotes inside normal quoted string we can do so without formality if they are different from the delimiting quotesotherwisewe must escape thema "single 'quotesare fine\"doubles\must be escaped 'single \'quotes\must be escaped"doublesare fine python uses newline as its statement terminatorexcept inside parentheses (())square brackets ([])braces ({})or triple quoted strings newlines can be used without formality in triple quoted stringsand we can include newlines in any string literal using the \ escape sequence all of python' escape sequences are shown in table in some situations--for examplewhen writing regular expressions--we need to create strings with lots of literal backslashes (regular expressions are the subject of this can be inconvenient since each one must be escapedimport re phone re compile("^((?:[(]\\ +[)])?\\ *\\ +(?:-\\ +)?)$"
8,618
the solution is to use raw strings these are quoted or triple quoted strings whose first quote is preceded by the letter inside such strings all characters are taken to be literalsso no escaping is necessary here is the phone regular expression using raw stringphone re compile( "^((?:[(]\ +[)])?\ *\ +(?:-\ +)?)$"if we want to write long string literal spread over two or more lines but without using triple quoted string there are couple of approaches we can taket "this is not the best way to join two long strings "together since it relies on ugly newline escapings ("this is the nice way to join two long strings "togetherit relies on string literal concatenation "notice that in the second case we must use parentheses to create single expression--without thems would be assigned only to the first stringand the second string would cause an indentationerror exception to be raised the python documentation' "idioms and anti-idiomshowto document recommends always using parentheses to spread statements of any kind over multiple lines rather than escaping newlinesa recommendation we endeavor to follow since py files default to using the utf- unicode encodingwe can write any unicode characters in our string literals without formality we can also put any unicode characters inside strings using hexadecimal escape sequences or using unicode names for exampleeuros \ {euro sign\ ac \ acprint(eurosin this case we could not use hexadecimal escape because they are limited to two digitsso they cannot exceed xff note that unicode character names are not case-sensitiveand spaces inside them are optional if we want to know the unicode code point (the integer assigned to the character in the unicode encodingfor particular character in stringwe can use the built-in ord(function for exampleord(euros[ ] hex(ord(euros[ ])' acsimilarlywe can convert any integer that represents valid code point into the corresponding unicode character using the built-in chr(functioncharacter encodings
8,619
data types "anarchists are chr( chr( 'anarchists are ascii( "'anarchists are \ \ 'if we enter on its own in idleit is output in its string formwhich for strings means the characters are output enclosed in quotes if we want only ascii characterswe can use the built-in ascii(function which returns the representational form of its argument using -bit ascii characters where possibleand using the shortest form of \xhh\uhhhhor \uhhhhhhhh escape otherwise we will see how to achieve precise control of string output later in this comparing strings str format( |strings support the usual comparison operators and >these operators compare strings byte by byte in memory unfortunatelytwo problems arise when performing comparisonssuch as when sorting lists of strings both problems afflict every programming language that uses unicode strings--neither is specific to python the first problem is that some unicode characters can be represented by two or more different byte sequences for examplethe character (unicode code point can be represented in utf- encoded bytes in three different ways[ xe xab][ xc ]and [ xcc afortunatelywe can solve this problem if we import the unicodedata module and call unicodedata normalize(with "nfkcas the first argument (this is normalization method--three others are also available"nfc""nfd"and "nfkd")and string containing the character using any of its valid byte sequencesthe function will return string that when represented as utf- encoded bytes will always be the byte sequence [ xc the second problem is that the sorting of some characters is language-specific one example is that in swedish is sorted after zwhereas in germana is sorted as if though were spelled ae another example is that although in english we sort as if it were oin danish and norwegian it is sorted after there are lots of problems along these linesand they can be complicated by the fact that sometimes the same application is used by people of different nationalities (who therefore expect different sorting orders)and sometimes strings are in mixture of languages ( some spanishothers english)and some characters (such as arrowsdingbatsand mathematical symbolsdon' really have meaningful sort positions as matter of policy--to prevent subtle mistakes--python does not make guesses in the case of string comparisonsit compares using the stringsinmemory byte representation this gives sort order based on unicode code character encodings
8,620
points which gives ascii sorting for english loweror uppercasing all the strings compared produces more natural english language ordering normalizing is unlikely to be needed unless the strings are from external sources like files or network socketsbut even in these cases it probably shouldn' be done unless there is evidence that it is needed we can of course customize python' sort methods as we will see in the whole issue of sorting unicode strings is explained in detail in the unicode collation algorithm document (unicode org/reports/tr |slicing and striding strings piece # we know from piece # that individual items in sequenceand therefore individual characters in stringcan be extracted using the item access operator ([]in factthis operator is much more versatile and can be used to extract not just one item or characterbut an entire slice (subsequenceof items or charactersin which context it is referred to as the slice operator first we will begin by looking at extracting individual characters index positions into string begin at and go up to the length of the string minus but it is also possible to use negative index positions--these count from the last character back toward the first given the assignment "light ray"figure shows all the valid index positions for string [- [- [ [ [- [- [- [ [ [- [- [ [ [- [- [ [ [ figure string index positions negative indexes are surprisingly usefulespecially - which always gives us the last character in string accessing an out-of-range index (or any index in an empty stringwill cause an indexerror exception to be raised the slice operator has three syntaxesseq[startseq[start:endseq[start:end:stepthe seq can be any sequencesuch as liststringor tuple the startendand step values must all be integers (or variables holding integerswe have used the first syntax alreadyit extracts the start-th item from the sequence the second syntax extracts slice from and including the start-th itemup to and excluding the end-th item we'll discuss the third syntax shortly
8,621
data types offers better solution the method takes sequence as an argument ( list or tuple of strings)and joins them together into single string with the string the method was called on between each one for exampletreatises ["arithmetica""conics""elements"join(treatises'arithmetica conics elements"--join(treatises'arithmetica--conics--elements"join(treatises'arithmeticaconicselementsthe first example is perhaps the most commonjoining with single characterin this case space the third example is pure concatenation thanks to the empty string which means that the sequence of strings are joined with nothing in between the str join(method can also be used with the built-in reversed(functionto reverse stringfor example"join(reversed( ))although the same result can be achieved more concisely by stridingfor examples[::- the operator provides string replications "= print( ==== * print( =================================================as the example showswe can also use the augmented assignment version of the replication operator when applied to stringsthe in membership operator returns true if its lefthand string argument is substring ofor equal toits right-hand string argument in cases where we want to find the position of one string inside anotherwe have two methods to choose from one is the str index(methodthis returns the index position of the substringor raises valueerror exception on failure the other is the str find(methodthis returns the index position of the substringor - on failure both methods take the string to find as their first argumentand can accept couple of optional arguments the second argument is the start position in the string being searchedand the third argument is the end position in the string being searched strings also support the operator for formatting this operator is deprecated and provided only to ease conversion from python to python it is not used in any of the book' examples
8,622
table string methods # syntax description capitalize(returns copy of str with the first letter capitalizedsee also the str title(method returns copy of centered in string of length width padded with spaces or optionally with char ( string of length )see str ljust()str rjust()and str format( center(widthchars count(tstartendreturns the number of occurrences of str in str (or in the start:end slice of sreturns bytes object that represents the string using the default encoding or using the specified encoding and handling errors according to the optional err argument bytes endswith(xstartendreturns true if (or the start:end slice of sends with str or with any of the strings in tuple xotherwisereturns false see also str startswith(character encodings expandtabssizereturns copy of with tabs replaced with spaces in multiples of or of size if specified find(tstartendreturns the leftmost position of in (or in the start:end slice of sor - if not found use str rfind(to find the rightmost position see also str index( formatreturns copy of formatted according to the given arguments this method and its arguments are covered in the next subsection returns the leftmost position of in (or in the start:end slice of sor raises valueerror if not found use str rindex(to search from the right see str find( encodeencodingerrs index(tstartendidentifiers and keywords isalnum(returns true if is nonempty and every character in is alphanumeric isalpha(returns true if is nonempty and every character in is alphabetic isdecimal(returns true if is nonempty and every character in is unicode base digit isdigit(returns true if is nonempty and every character in is an ascii digit isidentifier(returns true if is nonempty and is valid identifier islower(returns true if has at least one lowercaseable character and all its lowercaseable characters are lowercasesee also str isupper(type str format(
8,623
data types table string methods # syntax description isnumeric(returns true if is nonempty and every character in is numeric unicode character such as digit or fraction isprintable(returns true if is empty or if every character in is considered to be printableincluding spacebut not newline isspace(returns true if is nonempty and every character in is whitespace character istitle(returns true if is nonempty title-cased stringsee also str title(returns true if str has at least one uppercaseable character and all its uppercaseable characters are uppercasesee also str islower(returns the concatenation of every item in the sequence seqwith str (which may be emptybetween each one isupper( join(seqs ljustwidthchars lower(returns copy of left-aligned in string of length width padded with spaces or optionally with char ( string of length use str rjust(to right-align and str center(to center see also str format(returns lowercased copy of ssee also str upper( maketrans(companion of str translate()see text for details partitiontreturns tuple of three strings--the part of str before the leftmost str ttand the part of after tor if isn' in returns and two empty strings use str rpartition(to partition on the rightmost occurrence of replace(tunreturns copy of with every (or maximum of if givenoccurrences of str replaced with str split(tnreturns list of strings splitting at most times on str tif isn' givensplits as many times as possibleif isn' givensplits on whitespace use str rsplit(to split from the right--this makes difference only if is given and is less than the maximum number of splits possible splitlinesfreturns the list of lines produced by splitting on line terminatorsstripping the terminators unless is true startswithxstartendreturns true if (or the start:end slice of sstarts with str or with any of the strings in tuple xotherwisereturns false see also str endswith(
8,624
table string methods # syntax description strip(charsreturns copy of with leading and trailing whitespace (or the characters in str charsremovedstr lstrip(strips only at the startand str rstrip(strips only at the end swapcase(returns copy of with uppercase characters lowercased and lowercase characters uppercasedsee also str lower(and str upper( title(returns copy of where the first letter of each word is uppercased and all other letters are lowercasedsee str istitle( translate(companion of str maketrans()see text for details upper(returns an uppercased copy of ssee also str lower( zfill(wreturns copy of swhich if shorter than is padded with leading zeros to make it characters long which search method we use is purely matter of taste and circumstancealthough if we are looking for multiple index positionsusing the str index(method often produces cleaner codeas the following two equivalent functions illustratedef extract_from_tag(tagline)def extract_from_tag(tagline)opener "opener "closer "closer "tryi line find(openeri line index(openerif !- start len(openerstart len(openerj line index(closerstartj line find(closerstartreturn line[start:jif !- except valueerrorreturn line[start:jreturn none return none both versions of the extract_from_tag(function have exactly the same behavior for exampleextract_from_tag("red""what rose this is"returns the string "rosethe exception-handling version on the left separates out the code that does what we want from the code that handles errorsand the error return value version on the right intersperses what we want with error handling the methods str count()str endswith()str find()str rfind()str index()str rindex()and str startswith(all accept up to two optional argumentsa start position and an end position here are couple of equivalences to put this in contextassuming that is string
8,625
data types count(" " = [ :count(" " count(" " - = [ :- count(" "as we can seethe string methods that accept start and end indexes operate on the slice of the string specified by those indexes now we will look at another equivalencethis time to help clarify the behavior of str partition()--although we'll actually use str rpartition(exampleresult rpartition("/" rfind("/"if =- result """" elseresult [: ] [ ] [ :the leftand right-hand code snippets are not quite equivalent because the one on the right also creates new variablei notice that we can assign tuples without formalityand that in both cases we looked for the rightmost occurrence of if is the string "/usr/local/bin/firefox"both snippets produce the same result('/usr/local/bin''/''firefox'we can use str endswith((and str startswith()with single string argumentfor examples startswith("from:")or with tuple of strings here is statement that uses both str endswith(and str lower(to print filename if it is jpeg fileif filename lower(endswith((jpg"jpeg"))print(filename"is jpeg image"the is*(methods such as isalpha(and isspace(return true if the string they are called on has at least one characterand every character in the string meets the criterion for example" isdigit()"isdigit()"- isdigit()" isdigit((falsefalsefalsetruethe is*(methods work on the basis of unicode character classificationsso for examplecalling str isdigit(on the strings "\ {circled digit two} and " returns true for both of them for this reason we cannot assume that string can be converted to an integer when isdigit(returns true when we receive strings from external sources (other programsfilesnetwork connectionsand especially interactive users)the strings may have unwanted leading and trailing whitespace we can strip whitespace from the left using str lstrip()from the right using str rstrip()or from both ends using str strip(we can also give string as an argument to the strip methodsin which case every occurrence of every character given will be stripped from the appropriate end or ends for example
8,626
"\ no parking lstrip() rstrip() strip(('no parking ''\ no parking''no parking'"strip("[](){}"'unbracketedwe can also replace strings within strings using the str replace(method this method takes two string argumentsand returns copy of the string it is called on with every occurrence of the first string replaced with the second if the second argument is an empty string the effect is to delete every occurrence of the first string we will see examples of str replace(and some other string methods in the csv html py example in the examples section toward the end of the one frequent requirement is to split string into list of strings for examplewe might have text file of data with one record per line and each record' fields separated by asterisks this can be done using the str split(method and passing in the string to split on as its first argumentand optionally the maximum number of splits to make as the second argument if we don' specify the second argumentas many splits are made as possible here is an examplerecord "leo tolstoy**fields record split("*"fields ['leo tolstoy'''''now we can use str split(again on the date of birth and date of death to calculate how long he lived (give or take year)born fields[ split("-"born [' '' '' 'died fields[ split("-"print("lived about"int(died[ ]int(born[ ])"years"lived about years we had to use int(to convert the years from strings to integersbut other than that the snippet is straightforward we could have gotten the years directly from the fields listfor exampleyear_born int(fields[ split("-")[ ]the two methods that we did not summarize in tables and are str maketrans(and str translate(the str maketrans(method is used to create translation table which maps characters to characters it accepts onetwoor three argumentsbut we will show only the simplest (two argumentcall where the first argument is string containing characters to translate from and the second argument is string containing the characters to translate to csv html py example
8,627
data types both arguments must be the same length the str translate(method takes translation table as an argument and returns copy of its string with the characters translated according to the translation table here is how we could translate strings that might contain bengali digits to english digitstable "maketrans("\ {bengali digit zero}"\ {bengali digit one}\ {bengali digit two}"\ {bengali digit three}\ {bengali digit four}"\ {bengali digit five}\ {bengali digit six}"\ {bengali digit seven}\ {bengali digit eight}"\ {bengali digit nine}"" "print(" translate(table)prints print("\ {bengali digit two} \ {bengali digit four}"\ {bengali digit nine}translate(table)prints notice that we have taken advantage of python' string literal concatenation inside the str maketrans(call and inside the second print(call to spread strings over multiple lines without having to escape newlines or use explicit concatenation we called str maketrans(on an empty string because it doesn' matter what string it is called onit simply processes its arguments and returns translation table the str maketrans(and str translate(methods can also be used to delete characters by passing string containing the unwanted characters as the third argument to str maketrans(if more sophisticated character translations are requiredwe could create custom codec--see the codecs module documentation for more about this python has few other library modules that provide string-related functionality we've already briefly mentioned the unicodedata moduleand we'll show it in use in the next subsection other modules worth looking up are difflib which can be used to show differences between files or between stringsthe io module' io stringio class which allows us to read from or write to strings as though they were filesand the textwrap module which provides facilities for wrapping and filling strings there is also string module that has few useful constants such as ascii_letters and ascii_lowercase we will see examples of some of these modules in use in in additionpython provides excellent support for regular expressions in the re module-is dedicated to this topic string formatting with the str format(method |the str format(method provides very flexible and powerful way of creating strings using str format(is easy for simple casesbut for complex formatting we need to learn the formatting syntax the method requires
8,628
the str format(method returns new string with the replacement fields in its string replaced with its arguments suitably formatted for example"the novel '{ }was published in { }format("hard times" "the novel 'hard timeswas published in each replacement field is identified by field name in braces if the field name is simple integerit is taken to be the index position of one of the arguments passed to str format(so in this casethe field whose name was was replaced by the first argumentand the one with name was replaced by the second argument if we need to include braces inside format stringswe can do so by doubling them up here is an example"{{{ }}{ ;-}}format(" ' in braces"" ' not""{ ' in bracesi' not ;-}if we try to concatenate string and numberpython will quite rightly raise typeerror but we can easily achieve what we want using str format()"{ }{ }format("the amount due is $" 'the amount due is $ we can also concatenate strings using str format((although the str join(method is best for this) "threes ="{ { { } format("the" "tops" 'the three topshere we have used couple of string variablesbut in most of this section we'll use string literals for str format(examplessimply for the sake of convenience--just keep in mind that any example that uses string literal could use string variable in exactly the same way the replacement field can have any of the following general syntaxes{field_name{field_name!conversion{field_name:format_specification{field_name!conversion:format_specificationone other point to note is that replacement fields can contain replacement fields nested replacement fields cannot have any formattingtheir purpose is to allow for computed formatting specifications we will see an example of this
8,629
data types when we take detailed look at format specifications we will now study each part of the replacement field in turnstarting with field names field names field name can be either an integer corresponding to one of the str format(method' argumentsor the name of one of the method' keyword arguments we discuss keyword arguments in but they are not difficultso we will provide couple of examples here for completeness"{whoturned {agethis yearformat(who="she"age= 'she turned this year"the {whowas { last weekformat( who="boy"'the boy was last weekthe first example uses two keyword argumentswho and ageand the second example uses one positional argument (the only kind we have used up to nowand one keyword argument notice that in an argument listkeyword arguments always come after positional argumentsand of course we can make use of any arguments in any order inside the format string field names may refer to collection data types--for examplelists in such cases we can include an index (not slice!to identify particular itemstock ["paper""envelopes""notepads""pens""paper clips""we have { [ ]and { [ ]in stockformat(stock'we have envelopes and notepads in stockthe refers to the positional argumentso { [ ]is the stock list argument' second itemand { [ ]is the stock list argument' third item later on we will learn about python dictionaries these store key-value itemsand since they can be used with str format()we'll just show quick example here don' worry if it doesn' make senseit will once you've read dict(animal="elephant"weight= "the { [animal]weighs { [weight]}kgformat( 'the elephant weighs kgjust as we access list and tuple items using an integer position indexwe access dictionary items using key we can also access named attributes assuming we have imported the math and sys moduleswe can do this"math pi=={ pisys maxunicode=={ maxunicode}format(mathsys'math pi== sys maxunicode== dict type
8,630
so in summarythe field name syntax allows us to refer to positional and keyword arguments that are passed to the str format(method if the arguments are collection data types like lists or dictionariesor have attributeswe can access the part we want using [or notation this is illustrated in figure positional argument index { {title{ [ ]{ [capital]{ rateindex key attribute {color[ ]{point[ ]{book isbnkeyword argument name figure annotated format specifier field name examples from python it is possible to omit field namesin which case python will in effect put them in for ususing numbers starting from for example "{{{}format("python""can""count"'python can countif we are using python the format string used here would have to be "{ { { }using this technique is convenient for formatting one or two itemsbut the approach we will look at next is more convenient when several items are involvedand works just as well with python before finishing our discussion of string format field namesit is worth mentioning rather different way to get values into format string this involves using an advanced techniquebut one useful to learn as soon as possiblesince it is so convenient the local variables that are currently in scope are available from the built-in locals(function this function returns dictionary whose keys are local variable names and whose values are references to the variablesvalues now we can use mapping unpacking to feed this dictionary into the str format(method the mapping unpacking operator is *and it can be applied to mapping (such as dictionaryto produce key-value list suitable for passing to function for exampleelement "silvernumber "element {numberis {element}format(**locals()'element is silvermapping unpacking
8,631
data types the syntax may seem weird enough to make perl programmer feel at homebut don' worry--it is explained in all that matters for now is that we can use variable names in format strings and leave python to fill in their values simply by unpacking the dictionary returned by locals()--or some other dictionary--into the str format(method for examplewe could rewrite the "elephantexample we saw earlier to have much nicer format string with simpler field names parameter unpacking "the {animalweighs {weight}kgformat(** 'the elephant weighs kgunpacking dictionary into the str format(method allows us to use the dictionary' keys as field names this makes string formats much easier to understandand also easier to maintainsince they are not dependent on the order of the arguments notehoweverthat if we want to pass more than one argument to str format()only the last one can use mapping unpacking conversions decimal numbers when we discussed decimal decimal numbers we noticed that such numbers are output in one of two ways for exampledecimal decimal(" "decimal(' 'print(decimal decimal(" ") the first way that the decimal decimal is shown is in its representational form the purpose of this form is to provide string which if interpreted by python would re-create the object it represents python programs can evaluate snippets of python code or entire programsso this facility can be useful in some situations not all objects can provide reproducing representationin which case they provide string enclosed in angle brackets for examplethe representational form of the sys module is the string "the second way that decimal decimal is shown is in its string form this form is aimed at human readersso the concern is to show something that makes sense to people if data type doesn' have string form and string is requiredpython will use the representational form python' built-in data types know about str format()and when passed as an argument to this method they return suitable string to display themselves it is also straightforward to add str format(support to custom data types as we will see in in additionit is possible to override the data type' normal behavior and force it to provide either its string or its representational form this is done by adding conversion specifier to the field currently there are three such specifierss to force string formr to force representational formeval(
8,632
and to force representational form but only using ascii characters here is an example"{ { ! { ! { ! }format(decimal decimal(" ")" decimal(' 'decimal(' ')in this casedecimal decimal' string form produces the same string as the string it provides for str format(which is what commonly happens alsoin this particular examplethere is no difference between the representational and ascii representational forms since both use only ascii characters here is another examplethis time concerning string that contains the title of movie"held in the variable movie if we print the string using "{ }format(moviethe string will be output unchangedbut if we want to avoid non-ascii characters we can use either ascii(movieor "{ ! }format(movie)both of which will produce the string '\ ffb\ \ \ \ \ \ bso far we have seen how to put the values of variables into format stringand how to force string or representational forms to be used now we are ready to consider the formatting of the values themselves format specifications the default formatting of integersfloating-point numbersand strings is often perfectly satisfactory but if we want to exercise fine controlwe can easily do so using format specifications we will deal separately with formatting stringsintegersand floating-point numbersto make learning the details easier the the general syntax that covers all of them is shown in figure for stringsthe things that we can control are the fill characterthe alignment within the fieldand the minimum and maximum field widths string format specification is introduced with colon (:and this is followed by an optional pair of characters-- fill character (which may not be }and an alignment character for right alignthen comes an optional minimum width integerand if we want to specify maximum widththis comes last as period followed by an integer note that if we specify fill character we must also specify an alignment we omit the sign and type parts of the format specification because they have no effect on strings it is harmless (but pointlessto have colon without any of the optional elements let' see some exampless "the sword of truth"{ }format(sdefault formatting 'the sword of truth
8,633
data types fill align sign width precision type any character except left right center pad between sign and digits for numbers -pad numbers minimum field width force signsign if neededspace or as appropriate prefix ints with oor use commas for grouping maximum field width for stringsnumber of decimal places for floatingpoint numbers ints bcdnoxxfloats eefggnfigure the general form of format specification "{ : }format(sminimum width 'the sword of truth "{ :> }format(sright alignminimum width the sword of truth"{ :^ }format(scenter alignminimum width the sword of truth "{ :-^ }format(sfillcenter alignminimum width '---the sword of truth----"{ < }format(sfillleft alignminimum width 'the sword of truth "{ }format(smaximum width 'the sword in the penultimate example we had to specify the left alignment (even though this is the defaultif we left out the <we would have and this simply means maximum field width of characters as we noted earlierit is possible to have replacement fields inside format specifications this makes it possible to have computed formats herefor exampleare two ways of setting string' maximum width using maxwidth variablemaxwidth "{ }format( [:maxwidth]'the sword of"{ { }}format(smaxwidth'the sword ofthe first approach uses standard string slicingthe second uses an inner replacement field the grouping comma was introduced with python
8,634
for integersthe format specification allows us to control the fill characterthe alignment within the fieldthe signwhether to use nonlocale-aware comma separator to group digits (from python )the minimum field widthand the number base an integer format specification begins with colonafter which we can have an optional pair of characters-- fill character (which may not be }and an alignment character for right alignand for the filling to be done between the sign and the numbernext is an optional sign characterforces the output of the signoutputs the sign only for negative numbersand space outputs space for positive numbers and sign for negative numbers then comes an optional minimum width integer--this can be preceded by character to get the base prefix output (for binaryoctaland hexadecimal numbers)and by to get -padding thenfrom python comes an optional comma--if present this will cause the number' digits to be grouped into threes with comma separating each group if we want the output in base other than decimal we must add type character-- for binaryo for octalx for lowercase hexadecimaland for uppercase hexadecimalalthough for completenessd for decimal integer is also allowed there are two other type characterscwhich means that the unicode character corresponding to the integer should be outputand nwhich outputs numbers in localesensitive way (note that if is usedusing doesn' make sense we can get -padding in two different ways"{ : = }format( fillminimum width ' "{ : = }format(- fillminimum width '- "{ : }format( -pad and minimum width ' "{ : }format(- -pad and minimum width '- the first two examples have fill character of and fill between the sign and the number itself (=the second two examples have minimum width of and -padding here are some alignment examples"{ :*< }format( fillleft alignmin width ' *******"{ :*> }format( fillright alignmin width '******* "{ :*^ }format( fillcenter alignmin width '*** ****"{ :*^ }format(- fillcenter alignmin width '***- ***
8,635
data types here are some examples that show the effects of the sign characters"[{ }[{ }]format( - space or sign ' [- ]"[{ :+}[{ :+}]format( - force sign '[+ [- ]"[{ :-}[{ :-}]format( - sign if needed '[ [- ]and here are two examples that use some of the type characters"{ : { : { : { : }format( ' deface deface"{ :# { :# { :# { :# }format( ' xdeface xdefaceit is not possible to specify maximum field width for integers this is because doing so might require digits to be chopped offthereby rendering the integer meaningless if we are using python and use comma in the format specificationthe integer will use commas for grouping for example"{ :,' , , { :*> ,}format(int( )**** , , both fields have grouping appliedand in additionthe second field is padded with *sright alignedand given minimum width of characters this is very convenient for many scientific and financial programsbut it does not take into account the current locale for examplemany continental europeans would expect the thousands separator to be and the decimal separator to be the last format character available for integers (and which is also available for floating-point numbersis this has the same effect as when given an integer and the same effect as when given floating-point number what makes special is that it respects the current localeand will use the locale-specific decimal separator and grouping separator in the output it produces the default locale is called the localeand for this the decimal and grouping characters are period and an empty string we can respect the user' locale by starting our programs with the following two lines as the first executable statementsimport locale locale setlocale(locale lc_all""in multithreaded programs it is best to call locale setlocale(only onceat program start-upand before any additional threads have been startedsince the function is not usually thread-safe
8,636
passing an empty string as the locale tells python to try to automatically determine the user' locale ( by examining the lang environment variable)with fallback of the locale here are some examples that show the effects of different locales on an integer and floating-point numberxy ( locale setlocale(locale lc_all" " "{ : { : }format(xyc =" locale setlocale(locale lc_all"en_us utf- "en "{ : { : }format(xyen =" , , , , locale setlocale(locale lc_all"de_de utf- "de "{ : { : }format(xyde = , although is very useful for integersit is of more limited use with floatingpoint numbers because as soon as they become large they are output using exponential form for floating-point numbersthe format specification gives us control over the fill characterthe alignment within the fieldthe signwhether to use nonlocale aware comma separator to group digits (from python )the minimum field widththe number of digits after the decimal placeand whether to present the number in standard or exponential formor as percentage the format specification for floating-point numbers is the same as for integersexcept for two differences at the end after the optional minimum width--from python after the optional grouping comma--we can specify the number of digits after the decimal place by writing period followed by an integer we can also add type character at the ende for exponential form with lowercase ee for exponential form with an uppercase ef for standard floating-point formg for "generalform--this is the same as unless the number is very largein which case it is the same as --and gwhich is almost the same as gbut uses either or also available is %--this results in the number being multiplied by with the resultant number output in format with symbol appended here are few examples that show exponential and standard formsamount ( * math pi "[{ : }[{ : }]format(amount' + ]"[{ :*> }[{ :*> }]format(amount'[**** + [***** ]"[{ :*>+ }[{ :*>+ }]format(amount'[***+ + [****+ ]the first example has minimum width of characters and has digits after the decimal point the second example builds on the firstand adds fill character if we use fill character we must also have an alignment characterso we have specified align right (even though that is the default for numbers
8,637
data types the third example builds on the previous twoand adds the sign character to force the output of the sign in python decimal decimal numbers are treated by str format(as strings rather than as numbers this makes it quite tricky to get nicely formatted output from python decimal decimal numbers can be formatted as floatsincluding support for to get comma-separated groups here is an example--we have omitted the field name since we don' need it for python "{: }format(decimal decimal(" ")' , , , if we omitted the format character (or used the format character)the number would be formatted as ' + python does not provide any direct support for formatting complex numbers--support was added with python howeverwe can easily solve this by formatting the real and imaginary parts as individual floating-point numbers for example"{ real }{ imag: }jformat( + ' + "{ real }{ imag: }jformat jwe access each attribute of the complex number individuallyand format them both as floating-point numbersin this case with three digits after the decimal place we have also forced the sign to be output for the imaginary partwe must add on the ourselves python supports formatting complex numbers using the same syntax as for floats"{: }format( ee ' , ,, , jone slight drawback of this approach is that exactly the same formatting is applied to both the real and the imaginary partsbut we can always use the python technique of accessing the complex number' attributes individually if we want to format each one differently exampleprint_unicode py in the preceding subsubsections we closely examined the str format(method' format specificationsand we have seen many code snippets that show particular aspects in this subsubsection we will review small yet useful example that makes use of str format(so that we can see format specifications in
8,638
realistic context the example also uses some of the string methods we saw in the previous sectionand introduces function from the unicodedata module the program has just lines of executable code it imports two modulessys and unicodedataand defines one custom functionprint_unicode_table(we'll begin by looking at sample run to see what it doesthen we will look at the code at the end of the program where processing really startsand finally we will look at the custom function print_unicode py spoked decimal hex chr name -- four teardrop-spoked asterisk four balloon-spoked asterisk heavy four balloon-spoked asterisk four club-spoked asterisk eight spoked asterisk teardrop-spoked asterisk open centre teardrop-spoked asterisk heavy teardrop-spoked asterisk heavy teardrop-spoked pinwheel asterisk balloon-spoked asterisk eight teardrop-spoked propeller asterisk heavy eight teardrop-spoked propeller asterisk if run with no argumentsthe program produces table of every unicode characterstarting from the space character and going up to the character with the highest available code point if an argument is givenas in the exampleonly those rows in the table where the lowercased unicode character name contains the argument are printed word none if len(sys argv if sys argv[ in ("- ""--help")print("usage{ [string]format(sys argv[ ])word elseword sys argv[ lower(if word ! print_unicode_table(wordthis program assumes that the console uses the unicode utf- encoding unfortunatelythe windows console has poor utf- support as workaroundthe examples include print_unicode_uni pya version of the program that writes its output to file which can then be opened using utf- -savvy editorsuch as idle (file handling
8,639
data types after the imports and the creation of the print_unicode_table(functionexecution reaches the code shown here we begin by assuming that the user has not given word to match on the command line if command-line argument is given and is - or --helpwe print the program' usage information and set word to as flag to indicate that we are finished otherwisewe set the word to lowercase copy of the argument the user typed in if the word is not then we print the table when we print the usage information we use format specification that just has the format name--in this casethe position number of the argument we could have written the line like this insteadprint("usage{ [ ][string]format(sys argv)using this approach the first is the index position of the argument we want to useand [ is the index within the argumentand it works because sys argv is list def print_unicode_table(word)print("decimal hex chr print(--{ :^ }format("name"){ :-< }format("")code ord("end sys maxunicode while code endc chr(codename unicodedata name( "**unknown ***"if word is none or word in name lower()print("{ : { : { :^ { }formatcodename title())code + we've used couple of blank lines for the sake of clarity the first two lines of the function' suite print the title lines the first str format(prints the text "namecentered in field characters widewhereas the second one prints an empty string in field characters wideusing fill character of "-"and aligned left (we must give an alignment if we specify fill character an alternative approach for the second line is thisprint(--{ }format("- )here we have used the string replication operator (*to create suitable stringand simply inserted it into the format string third alternative would be to simply type in "-" and use literal string we keep track of unicode code points in the code variableinitializing it to the code point for space ( we set the end variable to be the highest
8,640
unicode code point available--this will vary depending on whether python was compiled to use the ucs- or the ucs- character encoding inside the while loop we get the unicode character that corresponds to the code point using the chr(function the unicodedata name(function returns the unicode character name for the given unicode characterits optional second argument is the name to use if no character name is defined if the user didn' specify word (word is none)or if they did and it is in lowercased copy of the unicode character namethen we print the corresponding row although we pass the code variable to the str format(method only onceit is used three times in the format stringfirst to print the code as an integer in field characters wide (the fill character defaults to spaceso we did not need to specify it)second to print the code as an uppercase hexadecimal number in field characters wideand third to print the unicode character that corresponds to the code--using the "cformat specifierand centered in field with minimum width of three characters notice that we did not have to specify the type "din the first format specificationthis is because it is the default for integer arguments the second argument is the character' unicode character nameprinted using "titlecasethat iswith the first letter of each word uppercasedand all other letters lowercased now that we are familiar with the versatile str format(methodwe will make great use of it throughout the rest of the book character encodings |ultimatelycomputers can store only bytesthat is -bit values whichif unsignedrange from to xff every character must somehow be represented in terms of bytes in the early days of computing the pioneers devised encoding schemes that assigned particular character to particular byte for exampleusing the ascii encodinga is represented by by and so on in the and western europe the latin- encoding was often usedits characters in the range - are the same as the corresponding characters in -bit asciiwith those in the range xa - xff used for accented characters and other symbols needed by those using non-english latin alphabets many other encodings have been devised over the yearsand now there are lots of them in use--howeverdevelopment has ceased for many of themin favor of unicode having all these different encodings has proved very inconvenientespecially when writing internationalized software one solution that has been almost universally adopted is the unicode encoding unicode assigns every character to an integer--called code point in unicode-speak--just like the earlier encodings but unicode is not limited to using one byte per characterand is therefore able to represent every character in every language in single encod
8,641
data types ingso unlike other encodingsunicode can handle characters from mixture of languagesrather than just one but how is unicode storedcurrentlyslightly more than unicode characters are definedso even using signed numbersa -bit integer is more than adequate to store any unicode code point so the simplest way to store unicode characters is as sequence of -bit integersone integer per character this sounds very convenient since it should produce one to one mapping of characters to -bit integerswhich would make indexing to particular character very fast howeverin practice things aren' so simplesince some unicode characters can be represented by one or by two code points--for examplee can be represented by the single code point xe or by two code points and ( and combining acute accentnowadaysunicode is usually stored both on disk and in memory using utf utf- or utf- the first of theseutf- is backward compatible with -bit ascii since its first code points are represented by single-byte values that are the same as the -bit ascii character values to represent all the other unicode charactersutf- uses twothreeor more bytes per character this makes utf- very compact for representing text that is all or mostly english the gtk library (used by the gnome windowing systemamong othersuses utf- and it seems that utf- is becoming the de facto standard format for storing unicode text in files--for exampleutf- is the default format for xmland many web pages these days use utf- lot of other softwaresuch as javauses ucs- (which in modern form is the same as utf- this representation uses two or four bytes per characterwith the most common characters represented by two bytes the utf- representation (also called ucs- uses four bytes per character using utf- or utf- for storing unicode in files or for sending over network connection has potential pitfallif the data is sent as integers then the endianness matters one solution to this is to precede the data with byte order mark so that readers can adapt accordingly this problem doesn' arise with utf- which is another reason why it is so popular python represents unicode using either ucs- (utf- formator ucs- (utf- format in factwhen using ucs- python uses slightly simplified version that always uses two bytes per character and so can only represent code points up to xffff when using ucs- python can represent all the unicode code points the maximum code point is stored in the read-only sys maxunicode attribute--if its value is then python was compiled to use ucs- if largerthen python is using ucs- the str encode(method returns sequence of bytes--actually bytes objectcovered in --encoded according to the encoding argument we supply using this method we can get some insight into the difference between encodingsand why making incorrect encoding assumptions can lead to errors
8,642
artist "tage asenartist encode("latin " 'tage \xc \xe nartist encode("cp " 'tage \ fs\ nartist encode("utf " 'tage \xc \ \xc \xa nartist encode("utf " '\xff\xfet\ \ \ \ \ \xc \ \ \xe \ \ before an opening quote signifies bytes literal rather than string literal as conveniencewhen creating bytes literals we can use mixture of printable ascii characters and hexadecimal escapes we cannot encode tage asen' name using the ascii encoding because it does not have the character or any accented charactersso attempting to do so will result in unicodeencodeerror exception being raised the latin- encoding (also known as iso- - is an -bit encoding that has all the necessary characters for this name on the other handartist erno'bank would be less fortunate since the 'character is not latin- character and so could not be successfully encoded both names can be successfully encoded using unicode encodingsof course noticethoughthat for utf- the first two bytes are the byte order mark--these are used by the decoding function to detect whether the data is bigor little-endian so that it can adapt accordingly it is worth noting couple more points about the str encode(method the first argument (the encoding nameis case-insensitiveand hyphens and underscores in the name are treated as equivalentso "us-asciiand "us_asciiare considered the same there are also many aliases--for example"latin""latin ""latin_ ""iso- - ""cp "and some others are all "latin- the method can also accept an optional second argument which is used to tell it how to handle errors for examplewe can encode any string into ascii if we pass second argument of "ignoreor "replace"--at the price of losing dataof course--or losslessly if we use "backslashreplacewhich replaces non-ascii characters with \ \uand \ escapes for exampleartist encode("ascii""ignore"will produce 'tage snand artist encode("ascii""replace"will produce 'tage ? ? 'whereas artist encode("ascii""backslashreplace"will produce 'tage \xc \xe (we can also get an ascii string using "{ ! }format(artist)which produces 'tage \xc \xe nthe complement of str encode(is bytes decode((and bytearray decode()which returns string with the bytes decoded using the given encoding for exampleprint( "tage \xc \ \xc \xa ndecode("utf ")tage asen
8,643
data types print( "tage \xc \xe ndecode("latin ")tage asen the differences between the -bit latin- cp (an ibm pc encoding)and utf- encodings make it clear that guessing encodings is not likely to be successful strategy fortunatelyutf- is becoming the de facto standard for plain text filesso later generations may not even know that other encodings ever existed python py files use utf- so python always knows the encoding to use with string literals this means that we can type any unicode characters into our strings--providing our editor supports this when python reads data from external sources such as socketsit cannot know what encoding is usedso it returns bytes which we can then decode accordingly for text files python takes softer approachusing the local encoding unless we specify an encoding explicitly fortunatelysome file formats specify their encoding for examplewe can assume that an xml file uses utf- unless the directive explicitly specifies different encoding so when reading xml we might extractsaythe first byteslook for an encoding specificationand if founddecode the file using the specified encodingotherwise falling back to decoding using utf- this approach should work for any xml or plain text file that uses any of the single byte encodings supported by pythonexcept for ebcdic-based encodings (cp cp and few others (cp cp cp cp cp hzshift-jis- shift-jisx unfortunatelythis approach won' work for multibyte encodings (such as utf- and utf- at least two python packages for automatically detecting file' encoding are available from the python package indexpypi python org/pypi examples ||in this section we will draw on what we have covered in this and the one beforeto present two small but complete programs to help consolidate what we have learned so far the first program is bit mathematicalbut it is quite short at around lines the second is concerned with text processing and is more substantialwith seven functions in around lines of code quadratic py |quadratic equations are equations of the form ax bx where describe parabolas the roots of such equations are derived from the formula it is possible to use other encodings see the python tutorial' "source code encodingtopic
8,644
- + - ac the ac part of the formula is called the discriminant--if it is positive there are two real rootsif it is zero there is one real rootand if it is negative there are two complex roots we will write program that accepts the aband factors from the user (with the and factors allowed to be )and then calculates and outputs the root or roots first we will look at sample runand then we will review the code quadratic py ax bx enter enter enter - - or - with factors - and the output (with some digits trimmedis - ( + jor (jthe output isn' quite as tidy as we' like--for examplerather than - it would be nicer to have xand we would prefer not to have any factors shown at all you will get the chance to fix these problems in the exercises now we will turn to the codewhich begins with three importsimport cmath import math import sys we need both the float and the complex math libraries since the square root functions for real and complex numbers are differentand we need sys for sys float_info epsilon which we need to compare floating-point numbers with we also need function that can get floating-point number from the userdef get_float(msgallow_zero) none while is nonetryx float(input(msg)if not allow_zero and abs(xsys float_info epsilonprint("zero is not allowed" none since the windows console has poor utf- supportthere are problems with couple of the characters ( and -that quadratic py uses we have provided quadratic_uni py which displays the correct symbols on linux and mac os xand alternatives (^ and ->on windows
8,645
data types except valueerror as errprint(errreturn this function will loop until the user enters valid floating-point number (such as - )and will accept only if allow_zero is true once the get_float(function is definedthe rest of the code is executed we'll look at it in three partsstarting with the user interactionprint("ax\ {superscript twobx " get_float("enter "falseb get_float("enter "truec get_float("enter "truethanks to the get_float(functiongetting the aband factors is simple the boolean second argument says whether is acceptable none none discriminant ( * ( cif discriminant = -( ( )elseif discriminant root math sqrt(discriminantelsediscriminant root cmath sqrt(discriminantx (- root( ax (- root( athe code looks bit different to the formula because we begin by calculating the discriminant if the discriminant is we know that we have one real solution and so we calculate it directly otherwisewe take the real or complex square root of the discriminant and calculate the two roots equation ("{ } \ {superscript two{ } { \ {rightwards arrowx { }"format(abcx if is not noneequation +or { }format( print(equationwe haven' done any fancy formatting since python' defaults for floating-point numbers are fine for this examplebut we have used unicode character names for couple of special characters
8,646
using str format(with mapping unpacking more robust alternative to using positional arguments with their index positions as field namesis to use the dictionary returned by locals() technique we saw earlier in the equation ("{ } \ {superscript two{ } { \ {rightwards arrowx { }"format(**locals()and if we are using python we could omit the field names and leave python to populate the fields using the positional arguments passed to str format(equation ("{} \ {superscript two{} { \ {rightwards arrowx {}"format(abcx this is convenientbut not as robust as using named parametersnor as versatile if we needed to use format specifications nonethelessfor many simple cases this syntax is both easy and useful csv html py |one common requirement is to take data set and present it using html in this subsection we will develop program that reads file that uses simple csv (comma separated valueformat and outputs an html table containing the file' data python comes with powerful and sophisticated module for handling csv and similar formats--the csv module--but here we will write all the code by hand the csv format we will support has one record per linewith each record divided into fields by commas each field can be either string or number strings must be enclosed in single or double quotes and numbers should be unquoted unless they contain commas commas are allowed inside stringsand must not be treated as field separators we assume that the first record contains field labels the output we will produce is an html table with text left-aligned (the default in htmland numbers right-alignedwith one row per record and one cell per field the program must output the html table' opening tagthen read each line of data and for each one output an html rowand at the end output the html table' closing tag we want the background color of the first row (which will display the field labelsto be light greenand the background of the data rows to alternate between white and light yellow we must also make sure that the special html characters ("&"""are properly escapedand we want strings to be tidied up bit here' tiny piece of sample data"country"," "," ", , , "antigua and barbuda", , , , ,
8,647
data types "argentina", , , , , "bahamasthe", , , , , "bahrain", , , , , assuming the sample data is in the file data/co -sample csvand given the command csv html py co -sample htmlthe file co -sample html will have contents similar to thiscountry argentina we've tidied the output slightly and omitted some lines where indicated by ellipses we have used very simple version of html--html transitionalwith no style sheet figure shows what the output looks like in web browser figure csv html py table in web browser now that we've seen how the program is used and what it doeswe are ready to review the code the program begins with the import of the sys modulewe won' show thisor any other imports from now onunless they are unusual or warrant discussion and the last statement in the program is single function callmain(although python does not need an entry point as some languages requireit is quite common in python programs to create function called main(and to call it to start off processing since no function can be called before it has been createdwe must make sure we call main(after the functions it relies on have
8,648
been defined the order in which the functions appear in the file ( the order in which they are createddoes not matter in the csv html py programthe first function we call is main(which in turn calls print_start(and then print_line(and print_line(calls extract_ fields(and escape_html(the program structure we have used is shown in figure import sys def main()def print_start()def print_line()calls def extract_fields()calls calls def escape_html()def print_end()main(figure the csv html py program' structure when python reads file it begins at the top so for this exampleit starts by performing the importthen it creates the main(functionand then it creates the other functions in the order in which they appear in the file when python finally reaches the call to main(at the end of the fileall the functions that main(will call (and all the functions that those functions will callnow exist execution as we normally think of it begins where the call to main(is made we will look at each function in turnstarting with main(def main()maxwidth print_start(count while truetryline input(if count = color "lightgreenelif count color "whiteelsecolor "lightyellow
8,649
data types print_line(linecolormaxwidthcount + except eoferrorbreak print_end(the maxwidth variable is used to constrain the number of characters in cell--if field is bigger than this we will truncate it and signify this by adding an ellipsis to the truncated text we'll look at the print_start()print_line()and print_end(functions in moment the while loop iterates over each line of input--this could come from the user typing at the keyboardbut we expect it to be redirected file we set the color we want to use and call print_line(to output the line as an html table row def print_start()print(""def print_end()print(""we could have avoided creating these two functions and simply put the relevant print(function calls in main(but we prefer to separate out the logic since this is more flexibleeven though it doesn' really matter in this small example def print_line(linecolormaxwidth)print("format(color)fields extract_fields(linefor field in fieldsif not fieldprint(""elsenumber field replace(","""tryx float(numberprint("{ : }format(round( ))except valueerrorfield field title(field field replace(and "and "if len(field<maxwidthfield escape_html(fieldelsefield "{ formatescape_html(field[:maxwidth])print("{ }format(field)print(""
8,650
we cannot use str split(","to split each line into fields because commas can occur inside quoted strings so we have farmed this work out to the extract_fields(function once we have list of the fields (as stringswith no surrounding quotes)we iterate over themcreating table cell for each one if field is emptywe output an empty cell if field is quotedit could be string or it could be number that has been quoted to allow for internal commasfor example" , to account for thiswe make copy of the field with commas removed and try to convert the field to float if the conversion is successful we output right-aligned cell with the field rounded to the nearest whole number and output it as an integer if the conversion fails we output the field as string in this case we use str title(to neaten the case of the letters and we replace the word and with and as correction to str title()' effect if the field isn' too long we use all of itotherwise we truncate it to maxwidth characters and add an ellipsis to signify the truncationand in either case we escape any special html characters the field might contain def extract_fields(line)fields [field "quote none for in lineif in "\"'"if quote is nonestart of quoted string quote elif quote =cend of quoted string quote none elsefield + other quote inside quoted string continue if quote is none and =","end of field fields append(fieldfield "elsefield + accumulating field if fieldfields append(fieldadding the last field return fields this function reads the line it is given character by characteraccumulating list of fields--each one string without any enclosing quotes the function copes with fields that are unquotedand with fields that are quoted with single or double quotesand correctly handles commas and quotes (single quotes in double quoted stringsdouble quotes in single quoted strings
8,651
data types def escape_html(text)text text replace("&""&amp;"text text replace("<""&lt;"text text replace(">""&gt;"return text this function straightforwardly replaces each special html character with the appropriate html entity we must of course replace ampersands firstalthough the order doesn' matter for the angle brackets python' standard library includes slightly more sophisticated version of this function--you'll get the chance to use it in the exercisesand will see it again in summary ||this began by showing the list of python' keywords and described the rules that python applies to identifiers thanks to python' unicode supportidentifiers are not limited to subset of characters from small character set like ascii or latin- we also described python' int data typewhich differs from similar types in most other languages in that it has no intrinsic size limitation python integers can be as large as the machine' memory will allowand it is perfectly feasible to work with numbers that are hundreds of digits long all of python' most basic data types are immutablebut this is rarely noticable since the augmented assignment operators (+=*=-=/=and othersmeans that we can use very natural syntax while behind the scenes python creates result objects and rebinds our variables to them literal integers are usually written as decimal numbersbut we can write binary literals using the prefixoctal literals using the prefixand hexadecimal literals using the prefix when two integers are divided using /the result is always float this is different from many other widely used languagesbut helps to avoid some quite subtle bugs that can occur when division silently truncates (and if we want integer division we can use the /operator python has bool data type which can hold either true or false python has three logical operatorsandorand notof which the two binary operators (and and oruse short-circuit logic three kinds of floating-point numbers are availablefloatcomplexand decimal decimal the most commonly used is floatthis is double-precision floating-point number whose exact numerical characteristics depend on the underlying cc#or java library that python was built with complex numbers are represented as two floatsone holding the real value and the other the imaginary value the decimal decimal type is provided by the decimal module
8,652
these numbers default to having decimal places of accuracybut this can be increased or decreased to suit our needs all three floating-point types can be used with the appropriate built-in mathematical operators and functions and in additionthe math module provides variety of trigonometrichyperbolicand logarithmic functions that can be used with floatsand the cmath module provides similar set of functions for complex numbers most of the was devoted to strings python string literals can be created using single quotes or double quotesor using triple quoted string if we want to include newlines and quotes without formality various escape sequences can be used to insert special characters such as tab (\tand newline (\ )and unicode characters both using hexadecimal escapes and unicode character names although strings support the same comparison operators as other python typeswe noted that sorting strings that contain non-english characters can be problematic since strings are sequencesthe slicing operator ([]can be used to slice and stride strings with very simple yet powerful syntax strings can also be concatenated with the operator and replicated with the operatorand we can also use the augmented assignment versions of these operators (+and *=)although the str join(method is more commonly used for concatenation strings have many other methodsincluding some for testing string properties ( str isspace(and str isalpha())some for changing case ( str lower(and str title())some for searching ( str find(and str index())and many others python' string support is really excellentenabling us to easily find and extract or compare whole strings or parts of stringsto replace characters or substringsand to split strings into list of substrings and to join lists of strings into single string probably the most versatile string method is str format(this method is used to create strings using replacement fields and variables to go in those fieldsand format specifications to precisely define the characteristics of each field which is replaced with value the replacement field name syntax allows us to access the method' arguments by position or by name (for keyword arguments)and to use an indexkeyor attribute name to access an argument item or attribute the format specifications allow us to specify the fill characterthe alignmentand the minimum field width furthermorefor numbers we can also control how the sign is outputand for floating-point numbers we can specify the number of digits after the decimal point and whether to use standard or exponential notation we also discussed the thorny issue of character encodings python py files use the unicode utf- encoding by default and so can have commentsidentifiersand data written in just about any human language we can convert string
8,653
data types into sequence of bytes using particular encoding using the str encode(methodand we can convert sequence of bytes that use particular encoding back to string using the bytes decode(method the wide variety of character encodings currently in use can be very inconvenientbut utf- is fast becoming the de facto standard for plain text files (and is already the default for xml files)so this problem should diminish in the coming years in addition to the data types covered in this python provides two other built-in data typesbytes and bytearrayboth of which are covered in python also provides several collection data typessome built-in and others in the standard library in the next we will look at python' most important collection data types exercises || modify the print_unicode py program so that the user can enter several separate words on the command lineand print rows only where the unicode character name contains all the words the user has specified this means that we can type commands like thisprint_unicode_ans py greek symbol one way of doing this is to replace the word variable (which held noneor string)with words list don' forget to update the usage information as well as the code the changes involve adding less than ten lines of codeand changing less than ten more solution is provided in file print_unicode_ans py (windows and cross-platform users should modify print_unicode_uni pya solution is provided in print_unicode_uni_ans py modify quadratic py so that factors are not outputand so that negative factors are output as rather than as - this involves replacing the last five lines with about fifteen lines solution is provided in quadratic_ans py (windows and cross-platform users should modify quadratic_uni pya solution is provided in quadratic_uni_ans py delete the escape_html(function from csv html pyand use the xml sax saxutils escape(function from the xml sax saxutils module instead this is easyrequiring one new line (the import)five deleted lines (the unwanted function)and one changed line (to use xml sax saxutils escape(instead of escape_html() solution is provided in csv html _ans py modify csv html py againthis time adding new function called process_options(this function should be called from main(and should return tuple of two valuesmaxwidth (an intand format ( strwhen process_options(is called it should set default maxwidth of and default format of "--this will be used as the format specifier when outputting numbers
8,654
if the user has typed "-hor "--helpon the command linea usage message should be output and (nonenonereturned (in this case main(should do nothing otherwisethe function should read any command-line arguments that are given and perform the appropriate assignments for examplesetting maxwidth if "maxwidth=nis givenand similarly setting format if "format=sis given here is run showing the usage outputcsv html _ans py - usagecsv html py [maxwidth=int[format=stroutfile html maxwidth is an optional integerif specifiedit sets the maximum number of characters that can be output for string fieldsotherwise default of characters is used format is the format to use for numbersif not specified it defaults to fand here is command line with both options setcsv html _ans py maxwidth= format= mydata html don' forget to modify print_line(to make use of the format for outputting numbers--you'll need to pass in an extra argumentadd one lineand modify another line and this will slightly affect main(too the process_options(function should be about twenty-five lines (including about nine for the usage messagethis exercise may prove challenging for inexperienced programmers two files of test data are provideddata/co -sample csv and data/co -fromfossilfuels csv solution is provided in csv html _ans py in we will see how to use python' optparse module to simplify command-line processing
8,655
sequence types set types mapping types iterating and copying collections collection data types |||in the preceding we learned about python' most important fundamental data types in this we will extend our programming options by learning how to gather data items together using python' collection data types we will cover tuples and listsand also introduce new collection data typesincluding sets and dictionariesand cover all of them in depth in addition to collectionswe will also see how to create data items that are aggregates of other data items (like or +structs or pascal records)--such items can be treated as single unit when this is convenient for uswhile the items they contain remain individually accessible naturallywe can put aggregated items in collections just like any other items having data items in collections makes it much easier to perform operations that must be applied to all of the itemsand also makes it easier to handle collections of items read in from files we'll cover the very basics of text file handling in this as we need themdeferring most of the detail (including error handlingto after covering the individual collection data typeswe will look at how to iterate over collectionssince the same syntax is used for all of python' collectionsand we will also explore the issues and techniques involved in copying collections ||sequence types sequence type is one that supports the membership operator (in)the size function (len())slices ([])and is iterable python provides five built-in sequence typesbytearraybytesliststrand tuple--the first two are covered the definitions of what constitutes sequence typea set typeor mapping type given in this are practical but informal more formal definitions are given in
8,656
collection data types separately in some other sequence types are provided in the standard librarymost notablycollections namedtuple when iteratedall of these sequences provide their items in order strings we covered strings in the preceding in this section we will cover tuplesnamed tuplesand lists |tuples string slicing and striding tuple is an ordered sequence of zero or more object references tuples support the same slicing and striding syntax as strings this makes it easy to extract items from tuple like stringstuples are immutableso we cannot replace or delete any of their items if we want to be able to modify an ordered sequencewe simply use list instead of tupleor if we already have tuple but want to modify itwe can convert it to list using the list(conversion function and then apply the changes to the resultant list the tuple data type can be called as functiontuple()--with no arguments it returns an empty tuplewith tuple argument it returns shallow copy of the argumentand with any other argument it attempts to convert the given object to tuple it does not accept more than one argument tuples can also be created without using the tuple(function an empty tuple is created using empty parentheses()and tuple of one or more items can be created by using commas sometimes tuples must be enclosed in parentheses to avoid syntactic ambiguity for exampleto pass the tuple to functionwe would write function(( )figure shows the tuple "venus"- "green"" " and the index positions of the items inside the tuple strings are indexed in the same waybut whereas strings have character at every positiontuples have an object reference at each position [- [- [- [- [- 'venus- 'green' [ [ [ [ [ figure tuple index positions tuples provide just two methodst count( )which returns the number of times object occurs in tuple tand index( )which returns the index position of the leftmost occurrence of object in tuple --or raises valueerror exception if there is no in the tuple (these methods are also available for lists in additiontuples can be used with the operators (concatenation)(replication)and [(slice)and with in and not in to test for membership the +and *augmented assignment operators can be used even though tuples are shallow and deep copying
8,657
immutable--behind the scenes python creates new tuple to hold the result and sets the left-hand object reference to refer to itthe same technique is used when these operators are applied to strings tuples can be compared using the standard comparison operators (=>)with the comparisons being applied item by item (and recursively for nested items such as tuples inside tupleslet' look at few slicing examplesstarting with extracting one itemand slice of itemshair "black""brown""blonde""redhair[ 'blondehair[- :same ashair[ :('brown''blonde''red'these work the same for stringslistsand any other sequence type hair[: ]"gray"hair[ :(('black''brown')'gray'('blonde''red')here we tried to create new -tuplebut ended up with -tuple that contains two -tuples this happened because we used the comma operator with three items ( tuplea stringand tupleto get single tuple with all the items we must concatenate tupleshair[: ("gray",hair[ :('black''brown''gray''blonde''red'to make -tuple the comma is essentialbut in this caseif we had just put in the comma we would get typeerror (since python would think we were trying to concatenate string and tuple)so here we must have the comma and parentheses in this book (from this point on)we will use particular coding style when writing tuples when we have tuples on the left-hand side of binary operator or on the right-hand side of unary statementwe will omit the parenthesesand in all other cases we will use parentheses here are few examplesab ( left of binary operator del ab right of unary statement def ( )return xx * right of unary statement for xy in (( )( )( ))print(xyleft of binary operator
8,658
collection data types there is no obligation to follow this coding stylesome programmers prefer to always use parentheses--which is the same as the tuple representational formwhereas others use them only if they are strictly necessary eyes ("brown""hazel""amber""green""blue""gray"colors (haireyescolors[ ][ :- ('green''blue'here we have nested two tuples inside another tuple nested collections to any level of depth can be created like this without formality the slice operator [can be applied to slicewith as many used as necessary for examplethings ( - ("pea"( "xyz")"queue")things[ ][ ][ ][ 'zlet' look at this piece by piecebeginning with things[ which gives us the third item in the tuple (since the first item has index )which is itself tuple("pea"( "xyz")"queue"the expression things[ ][ gives us the second item in the things[ tuplewhich is again tuple( "xyz"and things[ ][ ][ gives us the second item in this tuplewhich is the string "xyzfinallythings[ ][ ][ ][ gives us the third item (characterin the stringthat is"ztuples are able to hold any items of any data typeincluding collection types such as tuples and listssince what they really hold are object references using complex nested data structures like this can easily become confusing one solution is to give names to particular index positions for examplemanufacturermodelseating ( minimummaximum ( aircraft ("airbus"" - "( )aircraft[seating][maximum this is certainly more meaningful than writing aircraft[ ][ ]but it involves creating lots of variables and is rather ugly we will see an alternative in the next subsection in the first two lines of the "aircraftcode snippetwe assigned to tuples in both statements when we have sequence on the right-hand side of an assignment (here we have tuples)and we have tuple on the left-hand sidewe say that the right-hand side has been unpacked sequence unpacking can be used to swap valuesfor exampleab (ba
8,659
strictly speakingthe parentheses are not needed on the rightbut as we noted earlierthe coding style used in this book is to omit parentheses for left-hand operands of binary operators and right-hand operands of unary statementsbut to use parentheses in all other cases we have already seen examples of sequence unpacking in the context of for in loops here is reminderfor xy in ((- )( )( - ))print(math hypot(xy)here we loop over tuple of -tuplesunpacking each -tuple into variables and named tuples | named tuple behaves just like plain tupleand has the same performance characteristics what it adds is the ability to refer to items in the tuple by name as well as by index positionand this allows us to create aggregates of data items the collections module provides the namedtuple(function this function is used to create custom tuple data types for examplesale collections namedtuple("sale""productid customerid date quantity price"the first argument to collections namedtuple(is the name of the custom tuple data type that we want to be created the second argument is string of spaceseparated namesone for each item that our custom tuples will take the first argumentand the names in the second argumentmust all be valid python identifiers the function returns custom class (data typethat can be used to create named tuples soin this casewe can treat sale just like any other python class (such as tuple)and create objects of type sale (in object-oriented termsevery class created this way is subclass of tupleobject-oriented programmingincluding subclassingis covered in here is an examplesales [sales append(sale( "" )sales append(sale( "" )here we have created list of two sale itemsthat isof two custom tuples we can refer to items in the tuples using index positions--for examplethe price of the first sale item is sales[ ][- ( )--but we can also use nameswhich makes things much clearer
8,660
collection data types total for sale in salestotal +sale quantity sale price print("total ${ }format(total)printstotal $ the clarity and convenience that named tuples provide are often useful for examplehere is the "aircraftexample from the previous subsection ( done the nice wayaircraft collections namedtuple("aircraft""manufacturer model seating"seating collections namedtuple("seating""minimum maximum"aircraft aircraft("airbus"" - "seating( )aircraft seating maximum when it comes to extracting named tuple items for use in strings there are three main approaches we can take print("{ { }format(aircraft manufactureraircraft model)airbus - here we have accessed each of the tuple' items that we are interested in using named tuple attribute access this gives us the shortest and simplest format string (and in python we could reduce this format string to just "{{}but this approach means that we must look at the arguments passed to str format(to see what the replacement texts will be this seems less clear than using named fields in the format string "{ manufacturer{ model}format(aircrafthere we have used single positional argument and used named tuple attribute names as field names in the format string this is much clearer than just using positional arguments alonebut it is pity that we must specify the positional value (even when using python fortunatelythere is nicer way named tuples have few private methods--that ismethods whose name begins with leading underscore one of them--namedtuple _asdict()--is so useful that we will show it in action "{manufacturer{model}format(**aircraft _asdict()using str format(with mapping unpacking the private namedtuple _asdict(method returns mapping of key-value pairswhere each key is the name of tuple element and each value is the cor private methods such as namedtuple _asdict(are not guaranteed to be available in all python versionsalthough the namedtuple _asdict(method is available in both python and
8,661
responding value we have used mapping unpacking to convert the mapping into key-value arguments for the str format(method although named tuples can be very convenientin we introduce object-oriented programmingand there we will go beyond simple named tuples and learn how to create custom data types that hold data items and that also have their own custom methods |lists string slicing and striding list is an ordered sequence of zero or more object references lists support the same slicing and striding syntax as strings and tuples this makes it easy to extract items from list unlike strings and tupleslists are mutableso we can replace and delete any of their items it is also possible to insertreplaceand delete slices of lists the list data type can be called as functionlist()--with no arguments it returns an empty listwith list argument it returns shallow copy of the argumentand with any other argument it attempts to convert the given object to list it does not accept more than one argument lists can also be created without using the list(function an empty list is created using empty brackets[]and list of one or more items can be created by using comma-separated sequence of items inside brackets another way of creating lists is to use list comprehension-- topic we will cover later in this subsection shallow and deep copying since all the items in list are really object referenceslistslike tuplescan hold items of any data typeincluding collection types such as lists and tuples lists can be compared using the standard comparison operators (=>)with the comparisons being applied item by item (and recursively for nested items such as lists or tuples inside lists given the assignment [- "kilo" " "["ram" "echo"] ]we get the list shown in figure [- [- [- [- [- [- - 'kilo ' ['ram' 'echo' [ [ [ [ [ [ figure list index positions and given this listlwe can use the slice operator--repeatedly if necessary--to access items in the listas the following equalities showl[ = [- =- [ = [- ='kilol[ ][ = [- ][ =' list comprehensions
8,662
collection data types [ ][ = [ ][- = [- ][ = [- ][- ='echol[ ][ ][ = [ ][ ][- = [- ][- ][ = [- ][- ][- ='clists can be nestediterated overand slicedthe same as tuples in factall the tuple examples presented in the preceding subsection would work exactly the same if we used lists instead of tuples lists support membership testing with in and not inconcatenation with +extending with +( the appending of all the items in the right-hand operand)and replication with and *lists can also be used with the built-in len(functionand with the del statement discussed here and described in the sidebar "deleting items using the del statement in additionlists provide the methods shown in table although we can use the slice operator to access items in listin some situations we want to take two or more pieces of list in one go this can be done by sequence unpacking any iterable (liststuplesetc can be unpacked using the sequence unpacking operatoran asterisk or star (*when used with two or more variables on the left-hand side of an assignmentone of which is preceded by *items are assigned to the variableswith all those left over assigned to the starred variable here are some examplesfirst*rest [ - firstrest ( [ - ]first*midlast "charles philip arthur george windsorsplit(firstmidlast ('charles'['philip''arthur''george']'windsor'*directoriesexecutable "/usr/local/bin/gvimsplit("/"directoriesexecutable (['''usr''local''bin']'gvim'when the sequence unpacking operator is used like thisthe expression *restand similar expressionsare called starred expressions python also has related concept called starred arguments for exampleif we have the following function that requires three argumentsdef product(abc)return hereis the multiplication operator we can call it with three argumentsor by using starred argumentsproduct( [ product(* product( * [ :]
8,663
table list methods syntax description append(xappends item to the end of list count(xreturns the number of times item occurs in list extend(ml + appends all of iterable ' items to the end of list lthe operator +does the same thing index(xstartendreturns the index position of the leftmost occurrence of item in list (or in the start:end slice of )otherwiseraises valueerror exception insert(ixinserts item into list at index position int pop(returns and removes the rightmost item of list pop(ireturns and removes the item at index position int in remove(xremoves the leftmost occurrence of item from list lor raises valueerror exception if is not found reverse(reverses list in-place sortsorts list in-placethis method accepts the same key and reverse optional arguments as the built-in sorted(sorted( in the first call we provide the three arguments normally in the second call we use starred argument--what happens here is that the three-item list is unpacked by the operatorso as far as the function is concerned it has received the three arguments it is expecting we could have achieved the same thing using -tuple and in the third call we pass the first argument conventionallyand the other two arguments by unpacking two-item slice of the list functions and argument passing are covered fully in there is never any syntactic ambiguity regarding whether operator is the multiplication or the sequence unpacking operator when it appears on the left-hand side of an assignment it is the unpacking operatorand when it appears elsewhere ( in function callit is the unpacking operator when used as unary operator and the multiplication operator when used as binary operator we have already seen that we can iterate over the items in list using the syntax for item in lif we want to change the items in list the idiom to use isfor in range(len( )) [iprocess( [ ]the built-in range(function returns an iterator that provides integers with one integer argumentnthe iterator range(returnsproducing range(
8,664
collection data types deleting items using the del statement although the name of the del statement is reminiscent of the word deleteit does not necessarily delete any data when applied to an object reference that refers to data item that is not collectionthe del statement unbinds the object reference from the data item and deletes the object reference for examplex object ref 'xcreatedint of value created del object ref 'xdeletedint ready for garbage collection traceback (most recent call last)nameerrorname 'xis not defined when an object reference is deletedpython schedules the data item to which it referred to be garbage-collected if no other object references refer to the data item whenor even ifgarbage collection takes place may be nondeterministic (depending on the python implementation)so if any cleanup is required we must handle it ourselves python provides two solutions to the nondeterminism one is to use try finally block to ensure that cleanup is doneand another is to use with statement as we will see in when del is used on collection data type such as tuple or listonly the object reference to the collection is deleted the collection and its items (and for those items that are themselves collectionsfor their itemsrecursivelyare scheduled for garbage collection if no other object references refer to the collection for mutable collections such as listsdel can be applied to individual items or slices--in both cases using the slice operator[if the item or items referred to are removed from the collectionand if there are no other object references referring to themthey are scheduled for garbage collection we could use this technique to increment all the numbers in list of integers for examplefor in range(len(numbers))numbers[ + since lists support slicingin several cases the same effect can be achieved using either slicing or one of the list methods for examplegiven the list woods ["cedar""yew""fir"]we can extend the list in either of two wayswoods +["kauri""larch"woods extend(["kauri""larch"]
8,665
in either case the result is the list ['cedar''yew''fir''kauri''larch'individual items can be added at the end of list using list append(items can be inserted at any index position within the list using list insert()or by assigning to slice of length for examplegiven the list woods ["cedar""yew""fir""spruce"]we can insert new item at index position ( as the list' third itemin either of two wayswoods[ : ["pine"woods insert( "pine"in both cases the result is the list ['cedar''yew''pine''fir''spruce'individual items can be replaced in list by assigning to particular index positionfor examplewoods[ "redwoodentire slices can be replaced by assigning an iterable to slicefor examplewoods[ : ["spruce""sugi""rimu"the slice and the iterable don' have to be the same length in all casesthe slice' items are removed and the iterable' items are inserted this makes the list shorter if the iterable has fewer items than the slice it replacesand longer if the iterable has more items than the slice to make what happens when assigning an iterable to slice really clearwe will consider one further example imagine that we have the list [" "" "" "" "" "" "]and that we assign an iterable (in this casea listto slice of it with the code [ : [" "" "firstthe slice is removedso behind the scenes the list becomes [' '' '' 'and then all the iterable' items are inserted at the slice' start positionso the resultant list is [' '' '' '' '' 'items can be removed in number of other ways we can use list pop(with no arguments to remove the rightmost item in list--the removed item is also returned similarly we can use list pop(with an integer index argument to remove (and returnan item at particular index position another way of removing an item is to call list remove(with the item to be removed as the argument the del statement can also be used to remove individual items--for exampledel woods[ ]--or to remove slices of items slices can also be removed by assigning an empty list to sliceso these two snippets are equivalentwoods[ : [del woods[ : in the left-hand snippet we have assigned an iterable (an empty listto sliceso first the slice is removedand since the iterable to insert is emptyno insertion takes place slicing and striding when we first covered slicing and stridingwe did so in the context of strings where striding wasn' very interesting but in the case of listsstriding allows us to access every -th item which can often be useful for examplesuppose we have the listx [ ]and we want to set every odd-indexed item ( [ ] [ ]etc to we can access every second item by
8,666
collection data types stridingfor examplex[:: but this will give us the items at index positions and so on we can fix this by giving an initial starting indexso now we have [ :: ]and this gives us slice of the items we want to set each item in the slice to we need list of sand this list must have exactly the same number of as there are items in the slice here is the complete solutionx[ :: [ len( [ :: ]now list is [ we used the replication operator *to produce list consisting of the number of we needed based on the length ( the number of itemsof the slice the interesting aspect is that when we assign the list [ to the strided slicepython correctly replaces [ ]' value with the first [ ]' value with the second and so on lists can be reversed and sorted in the same way as any other iterable using the built-in reversed(and sorted(functions covered in the iterators and iterable operations and functions subsection lists also have equivalent methodslist reverse(and list sort()both of which work in-place (so they don' return anything)the latter accepting the same optional arguments as sorted(one common idiom is to case-insensitively sort list of strings--for examplewe could sort the woods list like thiswoods sort(key=str lowerthe key argument is used to specify function which is applied to each itemand whose return value is used to perform the comparisons used when sorting as we noted in the previous section on string comparisons ( )for languages other than englishsorting strings in way that is meaningful to humans can be quite challenging for inserting itemslists perform best when items are added or removed at the end (list append()list pop()the worst performance occurs when we search for items in listfor exampleusing list remove(or list index()or using in for membership testing if fast searching or membership testing is requireda set or dict (both covered later in this may be more suitable collection choice alternativelylists can provide fast searching if they are kept in order by sorting them--python' sort algorithm is especially well optimized for sorting partially sorted lists--and using binary search (provided by the bisect module)to find items (in we will create an intrinsically sorted custom list class list comprehensions small lists are often created using list literalsbut longer lists are usually created programmatically for list of integers we can use list(range( ))or if we just need an integer iteratorrange(is sufficientbut for other lists using for in loop is very common supposefor examplethat we wanted to produce list of the leap years in given range we might start out like thisleaps [for year in range( )sorted(
8,667
if (year = and year ! or (year = )leaps append(yearwhen the built-in range(function is given two integer argumentsn and mthe iterator it returns produces the integers nn of courseif we knew the exact range beforehand we could use list literalfor exampleleaps [ list comprehension is an expression and loop with an optional condition enclosed in brackets where the loop is used to generate items for the listand where the condition can filter out unwanted items the simplest form of list comprehension is this[item for item in iterablethis will return list of every item in the iterableand is semantically no different from list(iterabletwo things that make list comprehensions more interesting and powerful are that we can use expressionsand we can attach condition--this takes us to the two general syntaxes for list comprehensions[expression for item in iterable[expression for item in iterable if conditionthe second syntax is equivalent totemp [for item in iterableif conditiontemp append(expressionnormallythe expression will either be or involve the item of coursethe list comprehension does not need the temp variable needed by the for in loop version now we can rewrite the code to generate the leaps list using list comprehension we will develop the code in three stages first we will generate list that has all the years in the given rangeleaps [ for in range( )this could also be done using leaps list(range( )now we'll add simple condition to get every fourth yearleaps [ for in range( if = finallywe have the complete versionleaps [ for in range( if ( = and ! or ( = )range(
8,668
collection data types using list comprehension in this case reduced the code from four lines to two-- small savingsbut one that can add up quite lot in large projects since list comprehensions produce liststhat isiterablesand since the syntax for list comprehensions requires an iterableit is possible to nest list comprehensions this is the equivalent of having nested for in loops for exampleif we wanted to generate all the possible clothing label codes for given sets of sexessizesand colorsbut excluding labels for the full-figured females whom the fashion industry routinely ignoreswe could do so using nested for in loopscodes [for sex in "mf"malefemale for size in "smlx"smallmediumlargeextra large if sex ="fand size =" "continue for color in "bgw"blackgraywhite codes append(sex size colorthis produces the item list['msb''msg''flw'the same thing can be achieved in just couple of lines using list comprehensioncodes [ for in "mffor in "smlxfor in "bgwif not ( ="fand =" ")hereeach item in the list is produced by the expression alsowe have used subtly different logic for the list comprehension where we skip invalid sex/size combinations in the innermost loopwhereas the nested for in loops version skips invalid combinations in its middle loop any list comprehension can be rewritten using one or more for in loops if the generated list is very largeit may be more efficient to generate each item as it is needed rather than produce the whole list at once this can be achieved by using generator rather than list comprehension we discuss this laterin set types || set type is collection data type that supports the membership operator (in)the size function (len())and is iterable in additionset types at least provide set isdisjoint(methodand support for comparisonsas well as support for the bitwise operators (which in the context of sets are used for unionintersectionetc python provides two built-in set typesthe mutable set type and the immutable frozenset when iteratedset types provide their items in an arbitrary order generators
8,669
only hashable objects may be added to set hashable objects are objects which have __hash__(special method whose return value is always the same throughout the object' lifetimeand which can be compared for equality using the __eq__(special method (special methods--methods whose name begins and ends with two underscores--are covered in all the built-in immutable data typessuch as floatfrozensetintstrand tupleare hashable and can be added to sets the built-in mutable data typessuch as dictlistand setare not hashable since their hash value changes depending on the items they containso they cannot be added to sets set types can be compared using the standard comparison operators (<<===!=>=>note that although =and !have their usual meaningswith the comparisons being applied item by item (and recursively for nested items such as tuples or frozen sets inside sets)the other comparison operators perform subset and superset comparisonsas we will see shortly |sets set is an unordered collection of zero or more object references that refer to hashable objects sets are mutableso we can easily add or remove itemsbut since they are unordered they have no notion of index position and so cannot be sliced or strided figure illustrates the set created by the following code snippets { "veil" - (" " )"sun"frozenset({ }) - (' ' frozenset({ }'sun'veil figure set is an unordered collection of unique items the set data type can be called as functionset()--with no arguments it returns an empty setwith set argument it returns shallow copy of the argumentand with any other argument it attempts to convert the given object to set it does not accept more than one argument nonempty sets can also be created without using the set(functionbut the empty set must be created shallow and deep copying
8,670
table set methods and operators syntax description add(xadds item to set if it is not already in clear(removes all the items from set copy(returns shallow copy of set difference(ts returns new set that has every item that is in set that is not in set removes every item that is in set from set difference_update(ts - discard(xremoves item from set if it is in ssee also set remove( intersection(ts intersection_update(ts & isdisjoint(ts issubset(ts < issuperset(ts > pop(returns and removes random item from set sor raises keyerror exception if is empty remove(xremoves item from set sor raises keyerror exception if is not in ssee also set discard( symmetric_ difference(ts returns new set that has every item that is in set and every item that is in set tbut excluding items that are in both sets symmetric_ difference_update(ts ^ union(ts makes set contain the symmetric difference of itself and set update(ts | returns new set that has each item that is in both set and set makes set contain the intersection of itself and set returns true if sets and have no items in common returns true if set is equal to or subset of set tuse to test whether is proper subset of returns true if set is equal to or superset of set tuse to test whether is proper superset of returns new set that has all the items in set and all the items in set that are not in set adds every item in set that is not in set sto set this method and its operator (if it has onecan also be used with frozensets shallow and deep copying
8,671
collection data types processingonce for each unique address assuming that the ip addresses are hashable and are in iterable ipsand that the function we want called for each one is called process_ip(and is already definedthe following code snippets will do what we wantalthough with subtly different behaviorseen set(for ip in ipsif ip not in seenseen add(ipprocess_ip(ipfor ip in set(ips)process_ip(ipfor the left-hand snippetif we haven' processed the ip address beforewe add it to the seen set and process itotherwisewe ignore it for the right-hand snippetwe only ever get each unique ip address to process in the first place the differences between the snippets are first that the left-hand snippet creates the seen set which the right-hand snippet doesn' needand second that the lefthand snippet processes the ip addresses in the order they are encountered in the ips iterable while the right-hand snippet processes them in an arbitrary order the right-hand approach is easier to codebut if the ordering of the ips iterable is important we must either use the left-hand approach or change the right-hand snippet' first line to something like for ip in sorted(set(ips))if this is sufficient to get the required order in theory the right-hand approach might be slower if the number of items in ips is very largesince it creates the set in one go rather than incrementally sets are also used to eliminate unwanted items for exampleif we have list of filenames but don' want any makefiles included (perhaps because they are generated rather than handwritten)we might writefilenames set(filenamesfor makefile in {"makefile""makefile""makefile"}filenames discard(makefilethis code will remove any makefile that is in the list using any of the standard capitalizations it will do nothing if no makefile is in the filenames list the same thing can be achieved in one line using the set difference (-operatorfilenames set(filenames{"makefile""makefile""makefile"we can also use set remove(to remove itemsalthough this method raises keyerror exception if the item it is asked to remove is not in the set
8,672
set comprehensions in addition to creating sets by calling set()or by using set literalwe can also create sets using set comprehensions set comprehension is an expression and loop with an optional condition enclosed in braces like list comprehensionstwo syntaxes are supported{expression for item in iterable{expression for item in iterable if conditionwe can use these to achieve filtering effect (providing the order doesn' matterhere is an examplehtml { for in files if lower(endswith((htm"html"))given list of filenames in filesthis set comprehension makes the set html hold only those filenames that end in htm or htmlregardless of case just like list comprehensionsthe iterable used in set comprehension can itself be set comprehension (or any other kind of comprehension)so quite sophisticated set comprehensions can be created frozen sets | frozen set is set thatonce createdcannot be changed we can of course rebind the variable that refers to frozen set to refer to something elsethough frozen sets can only be created using the frozenset data type called as function with no argumentsfrozenset(returns an empty frozen setwith frozenset argument it returns shallow copy of the argumentand with any other argument it attempts to convert the given object to frozenset it does not accept more than one argument since frozen sets are immutablethey support only those methods and operators that produce result without affecting the frozen set or sets to which they are applied table ( lists all the set methods--frozen sets support frozenset copy()frozenset difference((-)frozenset intersection((&)frozenset isdisjoint()frozenset issubset((<=also for proper subsets)frozenset issuperset((>=also for proper supersets)frozenset union((|)and frozenset symmetric_difference((^)all of which are indicated by in the table if binary operator is used with set and frozen setthe data type of the result is the same as the left-hand operand' data type so if is frozen set and is setf will produce frozen set and will produce set in the case of the =and !operatorsthe order of the operands does not matterand = will produce true if both sets contain the same items shallow and deep copying
8,673
collection data types another consequence of the immutability of frozen sets is that they meet the hashable criterion for set itemsso sets and frozen sets can contain frozen sets we will see more examples of set use in the next sectionand also in the examples section mapping types || mapping type is one that supports the membership operator (inand the size function (len())and is iterable mappings are collections of key-value items and provide methods for accessing items and their keys and values when iteratedunordered mapping types provide their items in an arbitrary order python provides two unordered mapping typesthe built-in dict type and the standard library' collections defaultdict type newordered mapping typecollections ordereddictwas introduced with python this is dictionary that has the same methods and properties ( the same apias the built-in dictbut stores its items in insertion order we will use the term dictionary to refer to any of these types when the difference doesn' matter hashable objects only hashable objects may be used as dictionary keysso immutable data types such as floatfrozensetintstrand tuple can be used as dictionary keysbut mutable types such as dictlistand set cannot on the other handeach key' associated value can be an object reference referring to an object of any typeincluding numbersstringslistssetsdictionariesfunctionsand so on dictionary types can be compared using the standard equality comparison operators (=and !=)with the comparisons being applied item by item (and recursively for nested items such as tuples or dictionaries inside dictionariescomparisons using the other comparison operators (=>are not supported since they don' make sense for unordered collections such as dictionaries dictionaries | dict is an unordered collection of zero or more key-value pairs whose keys are object references that refer to hashable objectsand whose values are object references referring to objects of any type dictionaries are mutableso we can easily add or remove itemsbut since they are unordered they have no notion of index position and so cannot be sliced or strided api stands for application programming interfacea generic term used to refer to the public methods and properties that classes provideand to the parameters and return values of functions and methods for examplepython' documentation documents the apis that python provides
8,674
the dict data type can be called as functiondict()--with no arguments it returns an empty dictionaryand with mapping argument it returns dictionary based on the argumentfor examplereturning shallow copy if the argument is dictionary it is also possible to use sequence argumentproviding that each item in the sequence is itself sequence of two objectsthe first of which is used as key and the second of which is used as value alternativelyfor dictionaries where the keys are valid python identifierskeyword arguments can be usedwith the key as the keyword and the value as the key' value dictionaries can also be created using braces--empty braces{}create an empty dictionarynonempty braces must contain one or more commaseparated itemseach of which consists of keya literal colonand value another way of creating dictionaries is to use dictionary comprehension-- topic we will cover later in this subsection here are some examples to illustrate the various syntaxes--they all produce the same dictionaryshallow and deep copying keyword arguments dictionary comprehensions dict({"id" "name""washer""size" } dict(id= name="washer"size= dict([("id" )("name""washer")("size" )] dict(zip(("id""name""size")( "washer" )) {"id" "name""washer""size" dictionary is created using dictionary literal dictionary is created using keyword arguments dictionaries and are created from sequencesand dictionary is created from dictionary literal the built-in zip(function that is used to create dictionary returns list of tuplesthe first of which has the first items of each of the zip(function' iterable argumentsthe second of which has the second itemsand so on the keyword argument syntax (used to create dictionary is usually the most compact and convenientproviding the keys are valid identifiers figure illustrates the dictionary created by the following code snippetd {"root" "blue"[ " " ] "venus"- none"mars""rover"( ) dictionary keys are uniqueso if we add key-value item whose key is the same as an existing keythe effect is to replace that key' value with new value brackets are used to access individual values--for exampled["root"returns [ returns the string "venus"and [ causes keyerror exception to be raisedgiven the dictionary shown in figure brackets can also be used to add and delete dictionary items to add an item we use the operatorfor exampled[" " and to delete an item we use the del statement--for exampledel ["mars"will delete the item whose key is "marsfrom the dictionaryor raise keyerror exception if no item has that zip(
8,675
collection data types ( 'mars 'rover'venus - 'blue[ ' ' 'root none figure dictionary is an unsorted collection of (keyvalueitems with unique keys key items can also be removed (and returnedfrom the dictionary using the dict pop(method dictionaries support the built-in len(functionand for their keysfast membership testing with in and not in all the dictionary methods are listed in table because dictionaries have both keys and valueswe might want to iterate over dictionary by (keyvalueitemsby valuesor by keys for examplehere are two equivalent approaches to iterating by (keyvaluepairsfor item in items()print(item[ ]item[ ]for keyvalue in items()print(keyvalueiterating over dictionary' values is very similarfor value in values()print(valueto iterate over dictionary' keys we can use dict keys()or we can simply treat the dictionary as an iterable that iterates over its keysas these two equivalent code snippets illustratefor key in dprint(keyfor key in keys()print(keyif we want to change the values in dictionarythe idiom to use is to iterate over the keys and change the values using the brackets operator for examplehere is how we would increment every value in dictionary dassuming that all the values are numbersfor key in dd[key+
8,676
table dictionary methods syntax description clear(removes all items from dict copy(returns shallow copy of dict fromkeyssvreturns dict whose keys are the items in sequence and whose values are none or if is given shallow and deep copying get(kreturns key ' associated valueor none if isn' in dict get(kvreturns key ' associated valueor if isn' in dict items(returns view of all the (keyvaluepairs in dict keys(returns view of all the keys in dict pop(kreturns key ' associated value and removes the item whose key is kor raises keyerror exception if isn' in pop(kvreturns key ' associated value and removes the item whose key is kor returns if isn' in dict popitem(returns and removes an arbitrary (keyvaluepair from dict dor raises keyerror exception if is empty setdefaultkvthe same as the dict get(methodexcept that if the key is not in dict da new item is inserted with the key kand with value of none or of if is given update(aadds every (keyvaluepair from that isn' in dict to dand for every key that is in both and areplaces the corresponding value in with the one in -- can be dictionaryan iterable of (keyvaluepairsor keyword arguments values(returns view of all the values in dict the dict items()dict keys()and dict values(methods all return dictionary views dictionary view is effectively read-only iterable object that appears to hold the dictionary' items or keys or valuesdepending on the view we have asked for in generalwe can simply treat views as iterables howevertwo things make view different from normal iterable one is that if the dictionary the view refers to is changedthe view reflects the change the other is that key and item views support some set-like operations given dictionary view and set or dictionary view xthe supported operations arev intersection union dictionary views can be thought of--and used as--iterablesthey are discussed in the text
8,677
collection data types difference symmetric difference we can use the membership operatorinto see whether particular key is in dictionaryfor examplex in and we can use the intersection operator to see which keys from given set are in dictionary for exampled {fromkeys("abcd" set("acx"matches keys( ={' ' ' ' ' ' ' ' ={' '' '' 'matches ={' '' 'note that in the snippet' comments we have used alphabetical order--this is purely for ease of reading since dictionaries and sets are unordered dictionaries are often used to keep counts of unique items one such example of this is counting the number of occurrences of each unique word in file here is complete program (uniquewords pythat lists every word and the number of times it occurs in alphabetical order for all the files listed on the command lineimport string import sys words {strip string whitespace string punctuation string digits "\"'for filename in sys argv[ :]for line in open(filename)for word in line lower(split()word word strip(stripif len(word words[wordwords get(word for word in sorted(words)print("'{ }occurs { timesformat(wordwords[word])we begin by creating an empty dictionary called words then we create string that contains all those characters that we want to ignoreby concatenating some useful strings provided by the string module we iterate over each filename given on the command lineand over each line in each file see the sidebar "reading and writing text files for an explanation of the open(function we don' specify an encoding (because we don' know what each file' encoding will be)so we let python open each file using the default local encoding we split each lowercased line into wordsand then strip off the characters that we want to ignore from both ends of each word if the resultant word is at least three characters long we need to update the dictionary we cannot use the syntax words[word+ because this will raise keyerror exception the first time new word is encountered--after allwe can' increment the value of an item that does not yet exist in the dictionary so we use
8,678
reading and writing text files files are opened using the built-in open(functionwhich returns "file object(of type io textiowrapper for text filesthe open(function takes one mandatory argument--the filenamewhich may include path--and up to six optional argumentstwo of which we briefly cover here the second argument is the mode--this is used to specify whether the file is to be treated as text file or as binary fileand whether the file is to be opened for readingwritingappendingor combination of these character encodings for text filespython uses an encoding that is platform-dependent where possible it is best to specify the encoding using open()' encoding argumentso the syntaxes we normally use for opening files are thesefin open(filenameencoding="utf "fout open(filename" "encoding="utf "for reading text for writing text because open()' mode defaults to "read text"and by using keyword rather than positional argument for the encoding argumentwe can omit the other optional positional arguments when opening for reading and similarlywhen opening to write we need to give only the arguments we actually want to use (argument passing is covered in depth in once file is opened for reading in text modewe can read the whole file into single string using the file object' read(methodor into list of strings using the file object' readlines(method very common idiom for reading line by line is to treat the file object as an iteratorfor line in open(filenameencoding="utf ")process(linethis works because file object can be iterated overjust like sequencewith each successive item being string containing the next line from the file the lines we get back include the line termination character\ if we specify mode of " "the file is opened in "write textmode we write to file using the file object' write(methodwhich takes single string as its argument each line written should end with \ python automatically translates between \ and the underlying platform' line termination characters when reading and writing once we have finished using file object we can call its close(method--this will cause any outstanding writes to be flushed in small python programs it is very common not to bother calling close()since python does this automatically when the file object goes out of scope if problem occursit will be indicated by an exception being raised (file handling
8,679
collection data types subtler approach we call dict get(with default value of if the word is already in the dictionarydict get(will return the associated numberand this value plus will be set as the item' new value if the word is not in the dictionarydict get(will return the supplied default of and this value plus ( will be set as the value of new item whose key is the string held by word to clarifyhere are two code snippets that do the same thingalthough the code using dict get(is more efficientwords[wordwords get(word if word not in wordswords[word words[word+ in the next subsection where we cover default dictionarieswe will see an alternative solution once we have accumulated the dictionary of wordswe iterate over its keys (the wordsin sorted orderand print each word and the number of times it occurs using dict get(allows us to easily update dictionary valuesproviding the values are single items like numbers or strings but what if each value is itself collectionto demonstrate how to handle this we will look at program that reads html files given on the command line and prints list of each unique web site that is referred to in the files with list of the referring files listed indented below the name of each web site structurallythe program (external_sites pyis very similar to the unique words program we have just reviewed here is the main part of the codesites {for filename in sys argv[ :]for line in open(filename) while truesite none line find("if - +len("for in range(ilen(line))if not (line[jisalnum(or line[jin -")site line[ :jlower(break if site and in sitesites setdefault(siteset()add(filenamei elsebreak
8,680
we begin by creating an empty dictionary then we iterate over each file listed on the command line and each line within each file we must account for the fact that each line may refer to any number of web siteswhich is why we keep calling str find(until it fails if we find the string "(our starting index positionby the length of "succeeding character until we reach one that isn' valid for web site' name if we find site (and as simply sanity checkonly if it contains period)we add it to the dictionary we cannot use the syntax sites[siteadd(filenamebecause this will raise keyerror exception the first time new site is encountered--after allwe can' add to set that is the value of an item that does not yet exist in the dictionary so we must use different approach the dict setdefault(method returns an object reference to the item in the dictionary that has the given key (the first argumentif there is no such itemthe method creates new item with the key and sets its value either to noneor to the given default value (the second argumentin this case we pass default value of set()that isan empty set so the call to dict setdefault(always returns an object reference to valueeither one that existed before or new one (of courseif the given key is not hashable typeerror exception will be raised in this examplethe returned object reference always refers to set (an empty set the first time any particular keythat issiteis encountered)and we then add the filename that refers to the site to the site' set of filenames by using set we ensure that even if file refers to site repeatedlywe record the filename only once for the site to make the dict setdefault(method' functionality clearhere are two equivalent code snippetssites setdefault(siteset()add(fnameif site not in sitessites[siteset(sites[siteadd(fnamefor the sake of completenesshere is the rest of the programfor site in sorted(sites)print("{ is referred to in:format(site)for filename in sorted(sites[site]key=str lower)print({ }format(filename)each web site is printed with the files that refer to it printed indented underneath the sorted(call in the outer for in loop sorts all the dictionary' keys--whenever dictionary is used in context that requires an iterable it is the keys that are used if we want the iterable to be the (keyvalueitems or the valueswe can use dict items(or dict values(the inner for in loop iterates over the sorted filenames from the current site' set of filenames sorted(
8,681
using str format(with mapping unpacking collection data types although dictionary of web sites is likely to contain lot of itemsmany other dictionaries have only few items for small dictionarieswe can print their contents using their keys as field names and using mapping unpacking to convert the dictionary' key-value items into key-value arguments for the str format(method mapping unpacking greens dict(green="# "olive="# "lime="# ff "print("{green{olive{lime}format(**greens)# # # ff hereusing mapping unpacking (**has exactly the same effect as writing format(green=greens greenolive=greens olivelime=greens lime)but is easier to write and arguably clearer note that it doesn' matter if the dictionary has more keys than we needsince only those keys whose names appear in the format string are used dictionary comprehensions dictionary comprehension is an expression and loop with an optional condition enclosed in bracesvery similar to set comprehension like list and set comprehensionstwo syntaxes are supported{keyexpressionvalueexpression for keyvalue in iterable{keyexpressionvalueexpression for keyvalue in iterable if conditionhere is how we could use dictionary comprehension to create dictionary where each key is the name of file in the current directory and each value is the size of the file in bytesfile_sizes {nameos path getsize(namefor name in os listdir(")the os ("operating system"module' os listdir(function returns list of the files and directories in the path it is passedalthough it never includes or in the list the os path getsize(function returns the size of the given file in bytes we can avoid directories and other nonfile entries by adding conditionfile_sizes {nameos path getsize(namefor name in os listdir("if os path isfile(name)the os path module' os path isfile(function returns true if the path passed to it is that of fileand false otherwise--that isfor directorieslinksand so on dictionary comprehension can also be used to create an inverted dictionary for examplegiven dictionary dwe can produce new dictionary whose keys are ' values and whose values are ' keysos and os path modules
8,682
inverted_d {vk for kv in items()the resultant dictionary can be inverted back to the original dictionary if all the original dictionary' values are unique--but the inversion will fail with typeerror being raised if any value is not hashable just like list and set comprehensionsthe iterable in dictionary comprehension can be another comprehensionso all kinds of nested comprehensions are possible default dictionaries |default dictionaries are dictionaries--they have all the operators and methods that dictionaries provide what makes default dictionaries different from plain dictionaries is the way they handle missing keysin all other respects they behave identically to dictionaries (in object-oriented termsdefaultdict is subclass of dictobject-oriented programmingincluding subclassingis covered in if we use nonexistent ("missing"key when accessing dictionarya keyerror is raised this is useful because we often want to know whether key that we expected to be present is absent but in some cases we want every key we use to be presenteven if it means that an item with the key is inserted into the dictionary at the time we first access it for exampleif we have dictionary which does not have an item with key mthe code [mwill raise keyerror exception but if is suitably created default dictionaryif an item with key is in the default dictionarythe corresponding value is returned the same as for dictionary--but if is not key in the default dictionarya new item with key is created with default valueand the newly created item' value is returned uniquewords py earlier we wrote small program that counted the unique words in the files it was given on the command line the dictionary of words was created like thiswords {each key in the words dictionary was word and each value an integer holding the number of times the word had occurred in all the files that were read here' how we incremented whenever suitable word was encounteredwords[wordwords get(word we had to use dict get(to account for when the word was encountered the first time (where we needed to create new item with count of and for when the word was encountered subsequently (where we needed to add to the word' existing count
8,683
collection data types when default dictionary is createdwe can pass in factory function factory function is function thatwhen calledreturns an object of particular type all of python' built-in data types can be used as factory functionsfor exampledata type str can be called as str()--and with no argument it returns an empty string object the factory function passed to default dictionary is used to create default values for missing keys note that the name of function is an object reference to the function--so when we want to pass functions as parameterswe just pass the name when we use function with parenthesesthe parentheses tell python that the function should be called the program uniquewords py has one more line than the original uniquewords py program (import collections)and the lines for creating and updating the dictionary are written differently here is how the default dictionary is createdwords collections defaultdict(intthe words default dictionary will never raise keyerror if we were to write words["xyz"and there was no item with key "xyz"when the access is attempted and the key isn' foundthe default dictionary will immediately create new item with key "xyzand value (by calling int())and this value is what will be assigned to words[word+ now we no longer need to use dict get()instead we can simply increment the item' value the very first time word is encountereda new item is created with value (to which is immediately added)and on every subsequent access is added to whatever the current value happens to be we have now completed our review of all of python' built-in collection data typesand couple of the standard library' collection data types in the next section we will look at some issues that are common to all of the collection data types ordered dictionaries |the ordered dictionaries type--collections ordereddict--was introduced with python in fulfillment of pep ordered dictionaries can be used as drop-in replacements for unordered dicts because they provide the same api the difference between the two is that ordered dictionaries store their items in the order in which they were inserted-- feature that can be very convenient note that if an ordered dictionary is passed an unordered dict or keyword arguments when it is createdthe item order will be arbitrarythis is because under the hood python passes keyword arguments using standard unordered
8,684
dict similar effect occurs with the use of the update(method for these reasonspassing keyword arguments or an unordered dict when creating an ordered dictionary or using update(on one is best avoided howeverif we pass list or tuple of key-value -tuples when creating an ordered dictionarythe ordering is preserved (since they are passed as single item-- list or tuplehere' how to create an ordered dictionary using list of -tuplesd collections ordereddict([(' '- )(' ' )(' ' )]because we used single list as argument the key ordering is preserved it is probably more common to create ordered dictionaries incrementallylike thistasks collections ordereddict(tasks[ "backuptasks[ "scan emailtasks[ "build systemif we had created unordered dicts the same way and asked for their keysthe order of the returned keys would be arbitrary but for ordered dictionarieswe can rely on the keys to be returned in the same order they were inserted so for these examplesif we wrote list( keys())we are guaranteed to get the list [' '' '' ']and if we wrote list(tasks keys())we are guaranteed to get the list [ one other nice feature of ordered dictionaries is that if we change an item' value--that isif we insert an item with the same key as an existing key--the order is not changed so if we did tasks[ "daily backup"and then asked for the list of keyswe would get exactly the same list in exactly the same order as before if we want to move an item to the endwe must delete it and then reinsert it we can also call popitem(to remove and return the last key-value item in the ordered dictionaryor we can call popitem(last=false)in which case the first item will be removed and returned anotherslightly more specialized use for ordered dictionaries is to produce sorted dictionaries given dictionarydwe can convert it into sorted dictionary like thisd collections ordereddict(sorted( items())note that if we were to insert any additional keys they would be inserted at the endso after any insertionto preserve the sorted orderwe would have to re-create the dictionary by executing the same code we used to create it in the first place doing insertions and re-creating isn' quite as inefficient as it soundssince python' sorting algorithm is highly optimizedespecially for partially sorted databut it is still potentially expensive in generalusing an ordered dictionary to produce sorted dictionary makes sense only if we expect to iterate over the dictionary multiple timesand if we do not expect to do any insertions (or very few)once the sorted dictionary has
8,685
collection data types been created (an implementation of real sorted dictionary that automatically maintains its keys in sorted order is presented in iterating and copying collections ||once we have collections of data itemsit is natural to want to iterate over all the items they contain in this section' first subsection we will introduce some of python' iterators and the operators and functions that involve iterators another common requirement is to copy collection there are some subtleties involved here because of python' use of object references (for the sake of efficiency)so in this section' second subsectionwe will examine how to copy collections and get the behavior we want iterators and iterable operations and functions |an iterable data type is one that can return each of its items one at time any object that has an __iter__(methodor any sequence ( an object that has __getitem__(method taking integer arguments starting from is an iterable and can provide an iterator an iterator is an object that provides __next__(method which returns each successive item in turnand raises stopiteration exception when there are no more items table lists the operators and functions that can be used with iterables the order in which items are returned depends on the underlying iterable in the case of lists and tuplesitems are normally returned in sequential order starting from the first item (index position )but some iterators return the items in an arbitrary order--for exampledictionary and set iterators the built-in iter(function has two quite different behaviors when given collection data type or sequence it returns an iterator for the object it is passed--or raises typeerror if the object cannot be iterated this use arises when creating custom collection data typesbut is rarely needed in other contexts the second iter(behavior occurs when the function is passed callable ( function or method)and sentinel value in this case the function passed in is called once at each iterationreturning the function' return value each timeor raising stopiteration exception if the return value equals the sentinel when we use for item in iterable looppython in effect calls iter(iterableto get an iterator this iterator' __next__(method is then called at each loop iteration to get the next itemand when the stopiteration exception is raisedit is caught and the loop is terminated another way to get an iterator' next item is to call the built-in next(function here are two equivalent pieces of code (multiplying the values in list)one using for in loop and the other using an explicit iterator__iter__(
8,686
product for in [ ]product * print(productprints product iter([ ]while truetryproduct *next(iexcept stopiterationbreak print(productprints any (finiteiterableican be converted into tuple by calling tuple( )or can be converted into list by calling list(ithe all(and any(functions can be used on iterators and are often used in functional-style programming here are couple of usage examples that show all()any()len()min()max()and sum() [- - all( )any( )len( )min( )max( )sum( (truetrue - append( all( )any( )len( )min( )max( )sum( (falsetrue - of these little functionslen(is probably the most frequently used the enumerate(function takes an iterator and returns an enumerator object this object can be treated like an iteratorand at each iteration it returns -tuple with the tuple' first item the iteration number (by default starting from )and the second item the next item from the iterator enumerate(was called on let' look at enumerate()' use in the context of tiny but complete program the grepword py program takes word and one or more filenames on the command line and outputs the filenameline numberand line whenever the line contains the given word here' sample rungrepword py dom data/forenames txt data/forenames txt: :dominykas data/forenames txt: :dominik data/forenames txt: :domhnall data/forenames txt: :dominic data files data/forenames txt and data/surnames txt contain unsorted lists of namesone per line in will see two other implementations of this programgrepword- py and grepwordt pywhich spread the work over multiple processes and multiple threads functionalstyle programming
8,687
collection data types table common iterable operators and functions syntax description returns sequence that is the concatenation of sequences and returns sequence that is int concatenations of sequence in all(ireturns true if item is in iterable iuse not in to reverse the test returns true if every item in iterable evaluates to true any(ireturns true if any item in iterable evaluates to true enumerate(inormally used in for in loops to provide sequence of (instartdexitemtuples with indexes starting at or startsee text len(xreturns the "lengthof if is collection it is the number of itemsif is string it is the number of characters max(ikeyreturns the biggest item in iterable or the item with the biggest key(itemvalue if key function is given min(ikeyreturns the smallest item in iterable or the item with the smallest key(itemvalue if key function is given rangestartstopstepreturns an integer iterator with one argument (stop)the iterator goes from to stop with two arguments (startstopthe iterator goes from start to stop with three arguments it goes from start to stop in steps of step reversed(ireturns an iterator that returns the items from iterator in reverse order sorted(ireturns list of the items from iterator in sorted orderkey keyis used to provide dsu (decoratesortundecoratesorting reverseif reverse is true the sorting is done in reverse order sum(istartreturns the sum of the items in iterable plus start (which defaults to ) may not contain strings zip( returns an iterator of tuples using the iterators to ininsee text apart from the sys importthe program is just ten lines longif len(sys argv print("usagegrepword py word infile [infile infilen]]"sys exit(word sys argv[ for filename in sys argv[ :]for linoline in enumerate(open(filename)start= )if word in line
8,688
print("{ }:{ }:{ }format(filenamelinoline rstrip())we begin by checking that there are at least two command-line arguments if there are notwe print usage message and terminate the program the sys exit(function performs an immediate clean terminationclosing any open files it accepts an optional int argument which is passed to the calling shell reading and writing text files sidebar we assume that the first argument is the word the user is looking for and that the other arguments are the names of the files to look in we have deliberately called open(without specifying an encoding--the user might use wildcards to specify any number of fileseach potentially with different encodingso in this case we leave python to use the platform-dependent encoding the file object returned by the open(function in text mode can be used as an iteratorreturning one line of the file on each iteration by passing the iterator to enumerate()we get an enumerator iterator that returns the iteration number (in variable lino"line number"and line from the fileon each iteration if the word the user is looking for is in the linewe print the filenameline numberand the first characters of the line with trailing whitespace ( \nstripped the enumerate(function accepts an optional keyword argumentstartwhich defaults to we have used this argument set to since by conventiontext file line numbers are counted from quite often we don' need an enumeratorbut rather an iterator that returns successive integers this is exactly what the range(function provides if we need list or tuple of integerswe can convert the iterator returned by range(by using the appropriate conversion function here are few exampleslist(range( ))list(range( ))tuple(range( - - )([ ][ ]( - - )the range(function is most commonly used for two purposesto create lists or tuples of integersand to provide loop counting in for in loops for examplethese two equivalent examples ensure that list ' items are all non-negativefor in range(len( )) [iabs( [ ] while len( ) [iabs( [ ] + in both casesif list was originallysay[ - - - ]afterward it will be [ since we can unpack an iterable using the operatorwe can unpack the iterator returned by the range(function for exampleif we have function called calculate(that takes four argumentshere are some ways we could call it with arguments and
8,689
collection data types calculate( ( calculate(*tcalculate(*range( )in all three callsfour arguments are passed the second call unpacks -tupleand the third call unpacks the iterator returned by the range(function we will now look at small but complete program to consolidate some of the things we have covered so farand for the first time to explicitly write to file the generate_test_names py program reads in file of forenames and file of surnamescreating two listsand then creates the file test-names txt and writes random names into it we will use the random choice(function which takes random item from sequenceso it is possible that some duplicate names might occur first we'll look at the function that returns the lists of namesand then we will look at the rest of the program def get_forenames_and_surnames()forenames [surnames [for namesfilename in ((forenames"data/forenames txt")(surnames"data/surnames txt"))for name in open(filenameencoding="utf ")names append(name rstrip()return forenamessurnames tuple unpacking in the outer for in loopwe iterate over two -tuplesunpacking each -tuple into two variables even though the two lists might be quite largereturning them from function is efficient because python uses object referencesso the only thing that is really returned is tuple of two object references inside python programs it is convenient to always use unix-style pathssince they can be typed without the need for escapingand they work on all platforms (including windowsif we have path we want to present to the user insayvariable pathwe can always import the os module and call path replace("/"os septo replace forward slashes with the platform-specific directory separator forenamessurnames get_forenames_and_surnames(fh open("test-names txt"" "encoding="utf "for in range( )line "{ { }\nformat(random choice(forenames)random choice(surnames)fh write(line
8,690
reading and writing text files sidebar having retrieved the two lists we open the output file for writingand keep the file object in variable fh ("file handle"we then loop timesand in each iteration we create line to be written to the fileremembering to include newline at the end of every line we make no use of the loop variable iit is needed purely to satisfy the for in loop' syntax the preceding code snippetthe get_forenames_and_surnames(functionand an import statement constitute the entire program in the generate_test_names py program we paired items from two separate lists together into strings another way of combining items from two or more lists (or other iterablesis to use the zip(function the zip(function takes one or more iterables and returns an iterator that returns tuples the first tuple has the first item from every iterablethe second tuple the second item from every iterableand so onstopping as soon as one of the iterables is exhausted here is an examplefor in zip(range( )range( )range( ))print( ( ( ( ( although the iterators returned by the second and third range(calls can produce five items eachthe first can produce only fourso that limits the number of items zip(can return to four tuples here is modified version of the program to generate test namesthis time with each name occupying characters and followed by random year the program is called generate_test_names py and outputs the file test-names txt we have not shown the get_forenames_and_surnames(function or the open(call sinceapart from the output filenamethey are the same as before limit years list(range( ) for yearforenamesurname in ziprandom sample(yearslimit)random sample(forenameslimit)random sample(surnameslimit))name "{ { }format(forenamesurnamefh write("{ < { }\nformat(nameyear)we begin by setting limit on how many names we want to generate then we create list of years by making list of the years from to inclusiveand then replicating this list three times so that the final list has three occurrences of each year this is necessary because the random sample(function that we are using (instead of random choice()takes both an iterable and how
8,691
collection data types many items it is to produce-- number that cannot be less than the number of items the iterable can return the random sample(function returns an iterator that will produce up to the specified number of items from the iterable it is given--with no repeats so this version of the program will always produce unique names tuple unpacking str format( in the for in loop we unpack each tuple returned by the zip(function we want to limit the length of each name to charactersand to do this we must first create string with the complete nameand then set the maximum width for that string when we call str format(the second time we left-align each nameand for names shorter than characters we fill with periods the extra period ensures that names that occupy the full field width are still separated from the year by period we will conclude this subsection by mentioning two other iterable-related functionssorted(and reversed(the sorted(function returns list with the items sortedand the reversed(function simply returns an iterator that iterates in the reverse order to the iterator it is given as its argument here is an example of reversed()list(range( )[ list(reversed(range( ))[ the sorted(function is more sophisticatedas these examples showx [for in zip(range(- )range( )range( )) + [- - - - - sorted( [- - - - - sorted(xreverse=true[ - - - - - sorted(xkey=abs[ - - - - - in the preceding snippetthe zip(function returns -tuples(- )(- )and so on the +operator extends listthat isit appends each item in the sequence it is given to the list the first call to sorted(returns copy of the list using the conventional sort order the second call returns copy of the list in the reverse of the conventional sort order the last call to sorted(specifies "keyfunction which we will come back to in moment
8,692
notice that since python functions are objects like any otherthey can be passed as arguments to other functionsand stored in collections without formality recall that function' name is an object reference to the functionit is the parentheses that follow the name that tell python to call the function when key function is passed (in this case the abs(function)it is called once for every item in the list (with the item passed as the function' sole parameter)to create "decoratedlist then the decorated list is sortedand the sorted list without the decoration is returned as the result we are free to use our own custom function as the key functionas we will see shortly for examplewe can case-insensitively sort list of strings by passing the str lower(method as key if we have the listxof ["sloop""yawl""cutter""schooner""ketch"]we can sort it case-insensitively using dsu (decoratesortundecoratewith single line of code by passing key functionor do the dsu explicitlyas these two equivalent code snippets showx sorted(xkey=str lowertemp [for item in xtemp append((item lower()item) [for keyvalue in sorted(temp) append(valueboth snippets produce new list["cutter""ketch""schooner""sloop""yawl"]although the computations they perform are not identical because the right-hand snippet creates the temp list variable python' sort algorithm is an adaptive stable mergesort that is both fast and smartand it is especially well optimized for partially sorted lists-- very common case the "adaptivepart means that the sort algorithm adapts to circumstances--for exampletaking advantage of partially sorted data the "stablepart means that items that sort equally are not moved in relation to each other (after allthere is no need)and the "mergesortpart is the generic name for the sorting algorithm used when sorting collections of integersstringsor other simple types their "less thanoperator (<is used python can sort collections that contain collectionsworking recursively to any depth for examplex list(zip(( )("pram""dorie""kayak""canoe")) [( 'pram')( 'dorie')( 'kayak')( 'canoe')sorted( [( 'kayak')( 'pram')( 'canoe')( 'dorie')the algorithm was created by tim peters an interesting explanation and discussion of the algorithm is in the file listsort txt which comes with python' source code
8,693
collection data types python has sorted the list of tuples by comparing the first item of each tupleand when these are the sameby comparing the second item this gives sort order based on the integerswith the strings being tiebreakers we can force the sort to be based on the strings and use the integers as tiebreakers by defining simple key functiondef swap( )return [ ] [ the swap(function takes -tuple and returns new -tuple with the arguments swapped assuming that we have entered the swap(function in idlewe can now do thissorted(xkey=swap[( 'canoe')( 'dorie')( 'kayak')( 'pram')lists can also be sorted in-place using the list sort(methodwhich takes the same optional arguments as sorted(sorting can be applied only to collections where all the items can be compared with each othersorted([ - ]sorted([ "spanner"- ]returns[- raises typeerror although the first list has numbers of different types (int and float)these types can be compared with each other so that sorting list containing them works fine but the second list has string and this cannot be sensibly compared with numberand so typeerror exception is raised if we want to sort list that has integersfloating-point numbersand strings that contain numberswe can give float(as the key functionsorted([" "- " " "- " ]key=floatthis returns the list [- '- ' ' ' ' 'notice that the list' values are not changedso strings remain strings if any of the strings cannot be converted to number ( "spanner") valueerror exception will be raised copying collections object references |since python uses object referenceswhen we use the assignment operator (=)no copying takes place if the right-hand operand is literal such as string or numberthe left-hand operand is set to be an object reference that refers to the in-memory object that holds the literal' value if the right-hand operand is an object referencethe left-hand operand is set to be an object reference that refers to the same object as the right-hand operand one consequence of this is that assignment is very efficient
8,694
when we assign large collectionssuch as long liststhe savings are very apparent here is an examplesongs ["because""boys""carol"beatles songs beatlessongs (['because''boys''carol']['because''boys''carol']herea new object reference (beatleshas been createdand both object references refer to the same list--no copying has taken place since lists are mutablewe can apply change for examplebeatles[ "cayennebeatlessongs (['because''boys''cayenne']['because''boys''cayenne']we applied the change using the beatles variable--but this is an object reference referring to the same list as songs refers to so any change made through either object reference is visible to the other this is most often the behavior we wantsince copying large collections is potentially expensive it also meansfor examplethat we can pass list or other mutable collection data type as an argument to functionmodify the collection in the functionand know that the modified collection will be accessible after the function call has completed howeverin some situationswe really do want separate copy of the collection (or other mutable objectfor sequenceswhen we take slice--for examplesongs[: ]--the slice is always an independent copy of the items copied so to copy an entire sequence we can do thissongs ["because""boys""carol"beatles songs[:beatles[ "cayennebeatlessongs (['because''boys''cayenne']['because''boys''carol']for dictionaries and setscopying can be achieved using dict copy(and set copy(in additionthe copy module provides the copy copy(function that returns copy of the object it is given another way to copy the built-in collection types is to use the type as function with the collection to be copied as its argument here are some examplescopy_of_dict_d dict(dcopy_of_list_l list(lcopy_of_set_s set(snotethoughthat all of these copying techniques are shallow--that isonly object references are copied and not the objects themselves for immutable
8,695
collection data types data types like numbers and strings this has the same effect as copying (except that it is more efficient)but for mutable data types such as nested collections this means that the objects they refer to are referred to both by the original collection and by the copied collection the following snippet illustrates thisx [ [" "" "" "] [:shallow copy xy ([ [' '' '' ']][ [' '' '' ']] [ [ ][ 'qxy ([ [' '' '' ']][ [' '' '' ']]when list is shallow-copiedthe reference to the nested list [" "" "" "is copied this means that both and have as their third item an object reference that refers to this listso any changes to the nested list are seen by both and if we really need independent copies of arbitrarily nested collectionswe can deep-copyimport copy [ [" "" "" "] copy deepcopy(xy[ [ ][ 'qxy ([ [' '' '' ']][ [' '' '' ']]herelists and yand the list items they containare completely independent note that from now on we will use the terms copy and shallow copy interchangeably--if we mean deep copywe will say so explicitly examples ||we have now completed our review of python' built-in collection data typesand three of the standard library collection types (collections namedtuplecollections defaultdictand collections ordereddictpython also provides the collections deque typea double-ended queueand many other collection types are available from third parties and from the python package indexpypi python org/pypi but now we will look at couple of slightly longer examples that draw together many of the things covered in this and in the preceding one
8,696
the first program is about seventy lines long and involves text processing the second program is around ninety lines long and is mathematical in flavor between themthe programs make use of dictionarieslistsnamed tuplesand setsand both make great use of the str format(method from the preceding generate_usernames py |imagine we are setting up new computer system and need to generate usernames for all of our organization' staff we have plain text data file (utf encodingwhere each line represents record and fields are colon-delimited each record concerns one member of the staff and the fields are their unique staff idforenamemiddle name (which may be an empty field)surnameand department name here is an extract of few lines from an example data/users txt data file :albert:lukas:montgomery:legal :albert:lukas:montgomery:sales :nadelle::landale:warehousing the program must read in all the data files given on the command lineand for every line (recordmust extract the fields and return the data with suitable username each username must be unique and based on the person' name the output must be text sent to the consolesorted alphabetically by surname and forenamefor examplename id username landalenadelle ( nlandale montgomeryalbert ( almontgo montgomeryalbert ( almontgo each record has exactly five fieldsand although we could refer to them by numberwe prefer to use names to keep our code clearidforenamemiddlenamesurnamedepartment range( it is python convention that identifiers written in all uppercase characters are to be treated as constants we also need to create named tuple type for holding the data on each useruser collections namedtuple("user""username forename middlename surname id"we will see how the constants and the user named tuple are used when we look at the rest of the code
8,697
collection data types the program' overall logic is captured in the main(functiondef main()if len(sys argv= or sys argv[ in {"- ""--help"}print("usage{ file [file filen]]formatsys argv[ ])sys exit(usernames set(users {for filename in sys argv[ :]for line in open(filenameencoding="utf ")line line rstrip(if lineuser process_line(lineusernamesusers[(user surname lower()user forename lower()user id)user print_users(usersif the user doesn' provide any filenames on the command lineor if they type "-hor "--helpon the command linewe simply print usage message and terminate the program for each line readwe strip off any trailing whitespace ( \nand process only nonempty lines this means that if the data file contains blank lines they will be safely ignored we keep track of all the allocated usernames in the usernames set to ensure that we don' create any duplicates the data itself is held in the users dictionarywith each user (member of the staffstored as dictionary item whose key is tuple of the user' surnameforenameand idand whose value is named tuple of type user using tuple of the user' surnameforenameand id for the dictionary' keys means that if we call sorted(on the dictionarythe iterable returned will be in the order we want ( surnameforenameid)without us having to provide key function def process_line(lineusernames)fields line split(":"username generate_username(fieldsusernamesuser user(usernamefields[forename]fields[middlename]fields[surname]fields[id]return user since the data format for each record is so simpleand because we've already stripped the trailing whitespace from the linewe can extract the fields simply by splitting on the colons we pass the fields and the usernames set to the generate_username(functionand then we create an instance of the user named
8,698
tuple type which we then return to the caller (main())which inserts the user into the users dictionaryready for printing if we had not created suitable constants to hold the index positionswe would be reduced to using numeric indexesfor exampleuser user(usernamefields[ ]fields[ ]fields[ ]fields[ ]although this is certainly shorterit is poor practice first it isn' clear to future maintainers what each field isand second it is vulnerable to data file format changes--if the order or number of fields in record changesthis code will break everywhere it is used but by using named constants in the face of changes to the record struturewe would have to change only the values of the constantsand all uses of the constants would continue to work def generate_username(fieldsusernames)username ((fields[forename][ fields[middlename][: fields[surname]replace("-"""replace("'""")username original_name username[: lower(count while username in usernamesusername "{ }{ }format(original_namecountcount + usernames add(usernamereturn username we make first attempt at creating username by concatenating the first letter of the forenamethe first letter of the middle nameand the whole surnameand deleting any hyphens or single quotes from the resultant string the code for getting the first letter of the middle name is quite subtle if we had used fields[middlename][ we would get an indexerror exception for empty middle names but by using slice we get the first letter if there is oneor an empty string otherwise next we make the username lowercase and no more than eight characters long if the username is in use ( it is in the usernames set)we try the username with " tacked on at the endand if that is in use we try with " "and so on until we get one that isn' in use then we add the username to the set of usernames and return the username to the caller def print_users(users)namewidth usernamewidth print("{ :<{nw}{ :^ { :{uw}}format"name""id""username"nw=namewidthuw=usernamewidth)print("{ :-<{nw}{ :-< { :-<{uw}}format""nw=namewidthuw=usernamewidth)
8,699
collection data types for key in sorted(users)user users[keyinitial "if user middlenameinitial user middlename[ name "{ surname}{ forename}{ }format(userinitialprint("{ <{nw}({ id: }{ username:{uw}}formatnameusernw=namewidthuw=usernamewidth)once all the records have been processedthe print_users(function is calledwith the users dictionary passed as its parameter str format( the first print(statement prints the column titlesand the second print(statement prints hyphens under each title this second statement' str format(call is slightly subtle the string we give to be printed is ""that isthe empty string--we get the hyphens by printing the empty string padded with hyphens to the given widths next we use for in loop to print the details of each userextracting the key for each user' dictionary item in sorted order for convenience we create the user variable so that we don' have to keep writing users[keythroughout the rest of the function in the loop' first call to str format(we set the name variable to the user' name in surnameforename (and optional initialform we access items in the user named tuple by name once we have the user' name as single string we print the user' detailsconstraining each column(nameidusernameto the widths we want the complete program (which differs from what we have reviewed only in that it has some initial comment lines and some importsis in generate_usernames py the program' structure--read in data fileprocess each recordwrite output--is one that is very frequently usedand we will meet it again in the next example statistics py |suppose we have bunch of data files containing numbers relating to some processing we have doneand we want to produce some basic statistics to give us some kind of overview of the data each file uses plain text (ascii encodingwith one or more numbers per line (whitespace-separatedhere is an example of the kind of output we want to producecount mean median mode [ std dev