id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
2,600 | for loop can also iterate over the keys or both keys and valuesfor in spam keys()print(kcolor age for in spam items()print( ('color''red'('age' when you use the keys()values()and items(methodsa for loop can iterate over the keysvaluesor key-value pairs in dictionaryrespectively notice that the values in the dict_items value returned by the items(method are tuples of the key and value if you want true list from one of these methodspass its list-like return value to the list(function enter the following into the interactive shellspam {'color''red''age' spam keys(dict_keys(['color''age']list(spam keys()['color''age'the list(spam keys()line takes the dict_keys value returned from keys(and passes it to list()which then returns list value of ['color''age'you can also use the multiple assignment trick in for loop to assign the key and value to separate variables enter the following into the interactive shellspam {'color''red''age' for kv in spam items()print('keyk valuestr( )keyage value keycolor valuered checking whether key or value exists in dictionary recall from the previous that the in and not in operators can check whether value exists in list you can also use these operators to see whether certain key or value exists in dictionary enter the following into the interactive shellspam {'name''zophie''age' 'namein spam keys(true dictionaries and structuring data |
2,601 | true 'colorin spam keys(false 'colornot in spam keys(true 'colorin spam false in the previous examplenotice that 'colorin spam is essentially shorter version of writing 'colorin spam keys(this is always the caseif you ever want to check whether value is (or isn'ta key in the dictionaryyou can simply use the in (or not inkeyword with the dictionary value itself the get(method it' tedious to check whether key exists in dictionary before accessing that key' value fortunatelydictionaries have get(method that takes two argumentsthe key of the value to retrieve and fallback value to return if that key does not exist enter the following into the interactive shellpicnicitems {'apples' 'cups' ' am bringing str(picnicitems get('cups' )cups ' am bringing cups ' am bringing str(picnicitems get('eggs' )eggs ' am bringing eggs because there is no 'eggskey in the picnicitems dictionarythe default value is returned by the get(method without using get()the code would have caused an error messagesuch as in the following examplepicnicitems {'apples' 'cups' ' am bringing str(picnicitems['eggs']eggs traceback (most recent call last)file ""line in ' am bringing str(picnicitems['eggs']eggs keyerror'eggsthe setdefault(method you'll often have to set value in dictionary for certain key only if that key does not already have value the code looks something like thisspam {'name''pooka''age' if 'colornot in spamspam['color''black |
2,602 | first argument passed to the method is the key to check forand the second argument is the value to set at that key if the key does not exist if the key does existthe setdefault(method returns the key' value enter the following into the interactive shellspam {'name''pooka''age' spam setdefault('color''black''blackspam {'color''black''age' 'name''pooka'spam setdefault('color''white''blackspam {'color''black''age' 'name''pooka'the first time setdefault(is calledthe dictionary in spam changes to {'color''black''age' 'name''pooka'the method returns the value 'blackbecause this is now the value set for the key 'colorwhen spam setdefault('color''white'is called nextthe value for that key is not changed to 'white'because spam already has key named 'colorthe setdefault(method is nice shortcut to ensure that key exists here is short program that counts the number of occurrences of each letter in string open the file editor window and enter the following codesaving it as charactercount pymessage 'it was bright cold day in apriland the clocks were striking thirteen count {for character in messagecount setdefault(character count[charactercount[character print(countyou can view the execution of this program at the program loops over each character in the message variable' stringcounting how often each character appears the setdefault(method call ensures that the key is in the count dictionary (with default value of so the program doesn' throw keyerror error when count[charactercount[character is executed when you run this programthe output will look like this{' ',' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' dictionaries and structuring data |
2,603 | the space character appears timesand the uppercase letter appears time this program will work no matter what string is inside the message variableeven if the string is millions of characters longpretty printing if you import the pprint module into your programsyou'll have access to the pprint(and pformat(functions that will "pretty printa dictionary' values this is helpful when you want cleaner display of the items in dictionary than what print(provides modify the previous charactercount py program and save it as prettycharactercount py import pprint message 'it was bright cold day in apriland the clocks were striking thirteen count {for character in messagecount setdefault(character count[charactercount[character pprint pprint(countyou can view the execution of this program at this timewhen the program is runthe output looks much cleanerwith the keys sorted {' ',' ' ' ' ' ' --snip-' ' ' ' ' ' the pprint pprint(function is especially helpful when the dictionary itself contains nested lists or dictionaries if you want to obtain the prettified text as string value instead of displaying it on the screencall pprint pformat(instead these two lines are equivalent to each otherpprint pprint(somedictionaryvalueprint(pprint pformat(somedictionaryvalue) |
2,604 | even before the internetit was possible to play game of chess with someone on the other side of the world each player would set up chessboard at their home and then take turns mailing postcard to each other describing each move to do thisthe players needed way to unambiguously describe the state of the board and their moves in algebraic chess notationthe spaces on the chessboard are identified by number and letter coordinateas in figure - figure - the coordinates of chessboard in algebraic chess notation the chess pieces are identified by lettersk for kingq for queenr for rookb for bishopand for knight describing move uses the letter of the piece and the coordinates of its destination pair of these moves describes what happens in single turn (with white going first)for instancethe notation nf nc indicates that white moved knight to and black moved knight to on the second turn of the game there' bit more to algebraic notation than thisbut the point is that you can unambiguously describe game of chess without needing to be in front of chessboard your opponent can even be on the other side of the worldin factyou don' even need physical chess set if you have good memoryyou can just read the mailed chess moves and update boards you have in your imagination computers have good memories program on modern computer can easily store billions of strings like ' nf nc this is how computers can play chess without having physical chessboard they model data to represent chessboardand you can write code to work with this model this is where lists and dictionaries can come in for examplethe dictionary {' ''bking'' ''wqueen'' ''bbishop'' ''bqueen'' ''wking'could represent the chess board in figure - dictionaries and structuring data |
2,605 | figure - chess board modeled by the dictionary {' ''bking'' ''wqueen'' ''bbishop'' ''bqueen'' ''wking'but for another exampleyou'll use game that' little simpler than chesstic-tac-toe tic-tac-toe board tic-tac-toe board looks like large hash symbol (#with nine slots that can each contain an xan oor blank to represent the board with dictionaryyou can assign each slot string-value keyas shown in figure - 'top- 'top- 'top- 'mid- 'mid- 'mid- 'low- 'low- 'low-rfigure - the slots of tic-tac-toe board with their corresponding keys you can use string values to represent what' in each slot on the board' '' 'or ( spacethusyou'll need to store nine strings you can use dictionary of values for this the string value with the key 'top-rcan represent the top-right cornerthe string value with the key 'low-lcan represent the bottom-left cornerthe string value with the key 'mid-mcan represent the middleand so on |
2,606 | store this board-as- -dictionary in variable named theboard open new file editor windowand enter the following source codesaving it as tictactoe pytheboard {'top- '''top- '''top- '''mid- '''mid- '''mid- '''low- '''low- '''low- ''the data structure stored in the theboard variable represents the tic-tactoe board in figure - figure - an empty tic-tac-toe board since the value for every key in theboard is single-space stringthis dictionary represents completely clear board if player went first and chose the middle spaceyou could represent that board with this dictionarytheboard {'top- '''top- '''top- '''mid- '''mid- '' ''mid- '''low- '''low- '''low- ''the data structure in theboard now represents the tic-tac-toe board in figure - figure - the first move dictionaries and structuring data |
2,607 | look like thistheboard {'top- '' ''top- '' ''top- '' ''mid- '' ''mid- '' ''mid- '''low- '''low- '''low- '' 'the data structure in theboard now represents the tic-tac-toe board in figure - figure - player wins of coursethe player sees only what is printed to the screennot the contents of variables let' create function to print the board dictionary onto the screen make the following addition to tictactoe py (new code is in bold)theboard {'top- '''top- '''top- '''mid- '''mid- '''mid- '''low- '''low- '''low- ''def printboard(board)print(board['top- ''|board['top- ''|board['top- ']print('-+-+-'print(board['mid- ''|board['mid- ''|board['mid- ']print('-+-+-'print(board['low- ''|board['low- ''|board['low- ']printboard(theboardyou can view the execution of this program at /tictactoe when you run this programprintboard(will print out blank tic-tac-toe board -+-+-+-+ |
2,608 | pass it try changing the code to the followingtheboard {'top- '' ''top- '' ''top- '' ''mid- '' ''mid- '' ''mid- '''low- '''low- '''low- '' 'def printboard(board)print(board['top- ''|board['top- ''|board['top- ']print('-+-+-'print(board['mid- ''|board['mid- ''|board['mid- ']print('-+-+-'print(board['low- ''|board['low- ''|board['low- ']printboard(theboardyou can view the execution of this program at now when you run this programthe new board will be printed to the screen | | -+-+ | -+-+| because you created data structure to represent tic-tac-toe board and wrote code in printboard(to interpret that data structureyou now have program that "modelsthe tic-tac-toe board you could have organized your data structure differently (for exampleusing keys like 'top-leftinstead of 'top- ')but as long as the code works with your data structuresyou will have correctly working program for examplethe printboard(function expects the tic-tac-toe data structure to be dictionary with keys for all nine slots if the dictionary you passed was missingsaythe 'mid-lkeyyour program would no longer work | | -+-+traceback (most recent call last)file "tictactoe py"line in printboard(theboardfile "tictactoe py"line in printboard print(board['mid- ''|board['mid- ''|board['mid- ']keyerror'mid-lnow let' add code that allows the players to enter their moves modify the tictactoe py program to look like thistheboard {'top- '''top- '''top- '''mid- '''mid- '''mid- '''low- '''low- '''low- ''def printboard(board)print(board['top- ''|board['top- ''|board['top- ']print('-+-+-'dictionaries and structuring data |
2,609 | print('-+-+-'print(board['low- ''|board['low- ''|board['low- ']turn 'xfor in range( )printboard(theboardprint('turn for turn move on which space?'move input(theboard[moveturn if turn =' 'turn 'oelseturn 'xprintboard(theboardyou can view the execution of this program at the new code prints out the board at the start of each new turn gets the active player' move updates the game board accordingly and then swaps the active player before moving on to the next turn when you run this programit will look something like this-+-+-+-+turn for move on which spacemid- -+-+| -+-+--snip- | | -+-+ | | -+-+ | turn for move on which spacelow- | | -+-+ | | -+-+ | | this isn' complete tic-tac-toe game--for instanceit doesn' ever check whether player has won--but it' enough to see how data structures can be used in programs |
2,610 | if you are curiousthe source code for complete tic-tac-toe program is described in the resources available from nested dictionaries and lists modeling tic-tac-toe board was fairly simplethe board needed only single dictionary value with nine key-value pairs as you model more complicated thingsyou may find you need dictionaries and lists that contain other dictionaries and lists lists are useful to contain an ordered series of valuesand dictionaries are useful for associating keys with values for examplehere' program that uses dictionary that contains other dictionaries of what items guests are bringing to picnic the totalbrought(function can read this data structure and calculate the total number of an item being brought by all the guests allguests {'alice'{'apples' 'pretzels' }'bob'{'ham sandwiches' 'apples' }'carol'{'cups' 'apple pies' }def totalbrought(guestsitem)numbrought for kv in guests items()numbrought numbrought get(item return numbrought print('number of things being brought:'print(apples str(totalbrought(allguests'apples'))print(cups str(totalbrought(allguests'cups'))print(cakes str(totalbrought(allguests'cakes'))print(ham sandwiches str(totalbrought(allguests'ham sandwiches'))print(apple pies str(totalbrought(allguests'apple pies'))you can view the execution of this program at /guestpicnicinside the totalbrought(functionthe for loop iterates over the key-value pairs in guests inside the loopthe string of the guest' name is assigned to kand the dictionary of picnic items they're bringing is assigned to if the item parameter exists as key in this dictionaryits value (the quantityis added to numbrought if it does not exist as keythe get(method returns to be added to numbrought the output of this program looks like thisnumber of things being broughtapples cups cakes ham sandwiches apple pies this may seem like such simple thing to model that you wouldn' need to bother with writing program to do it but realize that this same totalbrought(function could easily handle dictionary that contains dictionaries and structuring data |
2,611 | having this information in data structure along with the totalbrought(function would save you lot of timeyou can model things with data structures in whatever way you likeas long as the rest of the code in your program can work with the data model correctly when you first begin programmingdon' worry so much about the "rightway to model data as you gain more experienceyou may come up with more efficient modelsbut the important thing is that the data model works for your program' needs summary you learned all about dictionaries in this lists and dictionaries are values that can contain multiple valuesincluding other lists and dictionaries dictionaries are useful because you can map one item (the keyto another (the value)as opposed to listswhich simply contain series of values in order values inside dictionary are accessed using square brackets just as with lists instead of an integer indexdictionaries can have keys of variety of data typesintegersfloatsstringsor tuples by organizing program' values into data structuresyou can create representations of real-world objects you saw an example of this with tic-tac-toe board practice questions what does the code for an empty dictionary look likewhat does dictionary value with key 'fooand value look likewhat is the main difference between dictionary and listwhat happens if you try to access spam['foo'if spam is {'bar' }if dictionary is stored in spamwhat is the difference between the expressions 'catin spam and 'catin spam keys()if dictionary is stored in spamwhat is the difference between the expressions 'catin spam and 'catin spam values()what is shortcut for the following codeif 'colornot in spamspam['color''black what module and function can be used to "pretty printdictionary values |
2,612 | for practicewrite programs to do the following tasks chess dictionary validator in this we used the dictionary value {' ''bking'' ''wqueen'' ''bbishop'' ''bqueen'' ''wking'to represent chess board write function named isvalidchessboard(that takes dictionary argument and returns true or false depending on if the board is valid valid board will have exactly one black king and exactly one white king each player can only have at most piecesat most pawnsand all pieces must be on valid space from ' ato ' 'that isa piece can' be on space ' zthe piece names begin with either 'wor 'bto represent white or blackfollowed by 'pawn''knight''bishop''rook''queen'or 'kingthis function should detect when bug has resulted in an improper chess board fantasy game inventory you are creating fantasy video game the data structure to model the player' inventory will be dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has for examplethe dictionary value {'rope' 'torch' 'gold coin' 'dagger' 'arrow' means the player has rope torches gold coinsand so on write function named displayinventory(that would take any possible "inventoryand display it like the followinginventory arrow gold coin rope torch dagger total number of items hintyou can use for loop to loop through all the keys in dictionary inventory py stuff {'rope' 'torch' 'gold coin' 'dagger' 'arrow' def displayinventory(inventory)print("inventory:"item_total for kv in inventory items()fill this part in print("total number of itemsstr(item_total)displayinventory(stuffdictionaries and structuring data |
2,613 | imagine that vanquished dragon' loot is represented as list of strings like thisdragonloot ['gold coin''dagger''gold coin''gold coin''ruby'write function named addtoinventory(inventoryaddeditems)where the inventory parameter is dictionary representing the player' inventory (like in the previous projectand the addeditems parameter is list like dragonloot the addtoinventory(function should return dictionary that represents the updated inventory note that the addeditems list can contain multiples of the same item your code could look something like thisdef addtoinventory(inventoryaddeditems)your code goes here inv {'gold coin' 'rope' dragonloot ['gold coin''dagger''gold coin''gold coin''ruby'inv addtoinventory(invdragonlootdisplayinventory(invthe previous program (with your displayinventory(function from the previous projectwould output the followinginventory gold coin rope ruby dagger total number of items |
2,614 | nipul at ing ings text is one of the most common forms of data your programs will handle you already know how to concatenate two string values together with the operatorbut you can do much more than that you can extract partial strings from string valuesadd or remove spacingconvert letters to lowercase or uppercaseand check that strings are formatted correctly you can even write python code to access the clipboard for copying and pasting text |
2,615 | two different programming projectsa simple clipboard that stores multiple strings of text and program to automate the boring chore of formatting pieces of text working with strings let' look at some of the ways python lets you writeprintand access strings in your code string literals typing string values in python code is fairly straightforwardthey begin and end with single quote but then how can you use quote inside stringtyping 'that is alice' cat won' workbecause python thinks the string ends after aliceand the rest ( cat 'is invalid python code fortunatelythere are multiple ways to type strings double quotes strings can begin and end with double quotesjust as they do with single quotes one benefit of using double quotes is that the string can have single quote character in it enter the following into the interactive shellspam "that is alice' cat since the string begins with double quotepython knows that the single quote is part of the string and not marking the end of the string howeverif you need to use both single quotes and double quotes in the stringyou'll need to use escape characters escape characters an escape character lets you use characters that are otherwise impossible to put into string an escape character consists of backslash (\followed by the character you want to add to the string (despite consisting of two charactersit is commonly referred to as singular escape character for examplethe escape character for single quote is \you can use this inside string that begins and ends with single quotes to see how escape characters workenter the following into the interactive shellspam 'say hi to bob\' mother python knows that since the single quote in bob\' has backslashit is not single quote meant to end the string value the escape characters \and \let you put single quotes and double quotes inside your stringsrespectively table - lists the escape characters you can use |
2,616 | escape character prints as \single quote \double quote \ tab \ newline (line break\backslash enter the following into the interactive shellprint("hello there!\nhow are you?\ni\' doing fine "hello therehow are youi' doing fine raw strings you can place an before the beginning quotation mark of string to make it raw string raw string completely ignores all escape characters and prints any backslash that appears in the string for exampleenter the following into the interactive shellprint( 'that is carol\' cat 'that is carol\' cat because this is raw stringpython considers the backslash as part of the string and not as the start of an escape character raw strings are helpful if you are typing string values that contain many backslashessuch as the strings used for windows file paths like ' :\users\al\desktopor regular expressions described in the next multiline strings with triple quotes while you can use the \ escape character to put newline into stringit is often easier to use multiline strings multiline string in python begins and ends with either three single quotes or three double quotes any quotestabsor newlines in between the "triple quotesare considered part of the string python' indentation rules for blocks do not apply to lines inside multiline string open the file editor and write the followingprint('''dear aliceeve' cat has been arrested for catnappingcat burglaryand extortion sincerelybob'''manipulating strings |
2,617 | like thisdear aliceeve' cat has been arrested for catnappingcat burglaryand extortion sincerelybob notice that the single quote character in eve' does not need to be escaped escaping single and double quotes is optional in multiline strings the following print(call would print identical text but doesn' use multiline stringprint('dear alice,\ \neve\' cat has been arrested for catnappingcat burglaryand extortion \ \nsincerely,\nbob'multiline comments while the hash character (#marks the beginning of comment for the rest of the linea multiline string is often used for comments that span multiple lines the following is perfectly valid python code"""this is test python program written by al sweigart al@inventwithpython com this program was designed for python not python ""def spam()"""this is multiline comment to help explain what the spam(function does ""print('hello!'indexing and slicing strings strings use indexes and slices the same way lists do you can think of the string 'helloworld!as list and each character in the string as an item with corresponding index the space and exclamation point are included in the character countso 'helloworld!is characters longfrom at index to at index |
2,618 | spam 'helloworld!spam[ 'hspam[ 'ospam[- '!spam[ : 'hellospam[: 'hellospam[ :'world!if you specify an indexyou'll get the character at that position in the string if you specify range from one index to anotherthe starting index is included and the ending index is not that' whyif spam is 'helloworld!'spam[ : is 'hellothe substring you get from spam[ : will include everything from spam[ to spam[ ]leaving out the comma at index and the space at index this is similar to how range( will cause for loop to terate up tobut not including note that slicing string does not modify the original string you can capture slice from one variable in separate variable try entering the following into the interactive shellspam 'helloworld!fizz spam[ : fizz 'helloby slicing and storing the resulting substring in another variableyou can have both the whole string and the substring handy for quickeasy access the in and not in operators with strings the in and not in operators can be used with strings just like with list values an expression with two strings joined using in or not in will evaluate to boolean true or false enter the following into the interactive shell'helloin 'helloworldtrue 'helloin 'hellotrue 'helloin 'helloworldfalse 'in 'spamtrue 'catsnot in 'cats and dogsfalse manipulating strings |
2,619 | putting strings inside other strings putting strings inside other strings is common operation in programming so farwe've been using the operator and string concatenation to do thisname 'alage 'hellomy name is name am str(ageyears old 'hellomy name is al am years old howeverthis requires lot of tedious typing simpler approach is to use string interpolationin which the % operator inside the string acts as marker to be replaced by values following the string one benefit of string interpolation is that str(doesn' have to be called to convert values to strings enter the following into the interactive shellname 'alage 'my name is % am % years old (nameage'my name is al am years old python introduced -stringswhich is similar to string interpolation except that braces are used instead of %swith the expressions placed directly inside the braces like raw stringsf-strings have an prefix before the starting quotation mark enter the following into the interactive shellname 'alage 'my name is {namenext year will be {age 'my name is al next year will be remember to include the prefixotherwisethe braces and their contents will be part of the string value'my name is {namenext year will be {age 'my name is {namenext year will be {age useful string methods several string methods analyze strings or create transformed string values this section describes the methods you'll be using most often |
2,620 | the upper(and lower(string methods return new string where all the letters in the original string have been converted to uppercase or lowercaserespectively nonletter characters in the string remain unchanged enter the following into the interactive shellspam 'helloworld!spam spam upper(spam 'helloworld!spam spam lower(spam 'helloworld!note that these methods do not change the string itself but return new string values if you want to change the original stringyou have to call upper(or lower(on the string and then assign the new string to the variable where the original was stored this is why you must use spam spam upper(to change the string in spam instead of simply spam upper((this is just like if variable eggs contains the value writing eggs does not change the value of eggsbut eggs eggs does the upper(and lower(methods are helpful if you need to make caseinsensitive comparison for examplethe strings 'greatand 'greatare not equal to each other but in the following small programit does not matter whether the user types greatgreator greatbecause the string is first converted to lowercase print('how are you?'feeling input(if feeling lower(='great'print(' feel great too 'elseprint(' hope the rest of your day is good 'when you run this programthe question is displayedand entering variation on greatsuch as greatwill still give the output feel great too adding code to your program to handle variations or mistakes in user inputsuch as inconsistent capitalizationwill make your programs easier to use and less likely to fail how are yougreat feel great too you can view the execution of this program at /convertlowercasethe isupper(and islower(methods will return boolean true value if the string has at least one letter and all the letters manipulating strings |
2,621 | false enter the following into the interactive shelland notice what each method call returnsspam 'helloworld!spam islower(false spam isupper(false 'helloisupper(true 'abc islower(true ' islower(false ' isupper(false since the upper(and lower(string methods themselves return stringsyou can call string methods on those returned string values as well expressions that do this will look like chain of method calls enter the following into the interactive shell'helloupper('hello'helloupper(lower('hello'helloupper(lower(upper('hello'hellolower('hello'hellolower(islower(true the isx(methods along with islower(and isupper()there are several other string methods that have names beginning with the word is these methods return boolean value that describes the nature of the string here are some common isx string methodsisalpha(returns true if the string consists only of letters and isn' blank returns true if the string consists only of letters and numbers and is not blank isdecimal(returns true if the string consists only of numeric characters and is not blank isspace(returns true if the string consists only of spacestabsand newlines and is not blank istitle(returns true if the string consists only of words that begin with an uppercase letter followed by only lowercase letters isalnum( |
2,622 | 'helloisalpha(true 'hello isalpha(false 'hello isalnum(true 'helloisalnum(true ' isdecimal(true isspace(true 'this is title caseistitle(true 'this is title case istitle(true 'this is not title caseistitle(false 'this is not title case eitheristitle(false the isx(string methods are helpful when you need to validate user input for examplethe following program repeatedly asks users for their age and password until they provide valid input open new file editor window and enter this programsaving it as validateinput pywhile trueprint('enter your age:'age input(if age isdecimal()break print('please enter number for your age 'while trueprint('select new password (letters and numbers only):'password input(if password isalnum()break print('passwords can only have letters and numbers 'in the first while loopwe ask the user for their age and store their input in age if age is valid (decimalvaluewe break out of this first while loop and move on to the secondwhich asks for password otherwisewe inform the user that they need to enter number and again ask them to enter their age in the second while loopwe ask for passwordstore the user' input in passwordand break out of the loop if the input was alpha numeric if it wasn'twe're not satisfiedso we tell the user the password needs to be alphanumeric and again ask them to enter password manipulating strings |
2,623 | enter your ageforty two please enter number for your age enter your age select new password (letters and numbers only)secr tpasswords can only have letters and numbers select new password (letters and numbers only)secr you can view the execution of this program at /validateinputcalling isdecimal(and isalnum(on variableswe're able to test whether the values stored in those variables are decimal or notalphanumeric or not herethese tests help us reject the input forty two but accept and reject secr tbut accept secr the startswith(and endswith(methods the startswith(and endswith(methods return true if the string value they are called on begins or ends (respectivelywith the string passed to the methodotherwisethey return false enter the following into the interactive shell'helloworld!startswith('hello'true 'helloworld!endswith('world!'true 'abc startswith('abcdef'false 'abc endswith(' 'false 'helloworld!startswith('helloworld!'true 'helloworld!endswith('helloworld!'true these methods are useful alternatives to the =equals operator if you need to check only whether the first or last part of the stringrather than the whole thingis equal to another string the join(and split(methods the join(method is useful when you have list of strings that need to be joined together into single string value the join(method is called on stringgets passed list of stringsand returns string the returned string |
2,624 | the following into the interactive shell'join(['cats''rats''bats']'catsratsbatsjoin(['my''name''is''simon']'my name is simon'abcjoin(['my''name''is''simon']'myabcnameabcisabcsimonnotice that the string join(calls on is inserted between each string of the list argument for examplewhen join(['cats''rats''bats']is called on the 'stringthe returned string is 'catsratsbatsremember that join(is called on string value and is passed list value (it' easy to accidentally call it the other way around the split(method does the oppositeit' called on string value and returns list of strings enter the following into the interactive shell'my name is simonsplit(['my''name''is''simon'by defaultthe string 'my name is simonis split wherever whitespace characters such as the spacetabor newline characters are found these whitespace characters are not included in the strings in the returned list you can pass delimiter string to the split(method to specify different string to split upon for exampleenter the following into the interactive shell'myabcnameabcisabcsimonsplit('abc'['my''name''is''simon''my name is simonsplit(' '['my na'' is si''on' common use of split(is to split multiline string along the newline characters enter the following into the interactive shellspam '''dear alicehow have you beeni am fine there is container in the fridge that is labeled "milk experiment please do not drink it sincerelybob''spam split('\ '['dear alice,''how have you beeni am fine ''there is container in the fridge''that is labeled "milk experiment "''''please do not drink it ''sincerely,''bob'passing split(the argument '\nlets us split the multiline string stored in spam along the newlines and return list in which each item corresponds to one line of the string manipulating strings |
2,625 | the partition(string method can split string into the text before and after separator string this method searches the string it is called on for the separator string it is passedand returns tuple of three substrings for the "before,"separator,and "aftersubstrings enter the following into the interactive shell'helloworld!partition(' '('hello'' ''orld!''helloworld!partition('world'('hello''world''!'if the separator string you pass to partition(occurs multiple times in the string that partition(calls onthe method splits the string only on the first occurrence'helloworld!partition(' '('hell'' ''world!'if the separator string can' be foundthe first string returned in the tuple will be the entire stringand the other two strings will be empty'helloworld!partition('xyz'('helloworld!'''''you can use the multiple assignment trick to assign the three returned strings to three variablesbeforesepafter 'helloworld!partition('before 'hello,after 'world!the partition(method is useful for splitting string whenever you need the parts beforeincludingand after particular separator string justifying text with the rjust()ljust()and center(methods the rjust(and ljust(string methods return padded version of the string they are called onwith spaces inserted to justify the text the first argument to both methods is an integer length for the justified string enter the following into the interactive shell'hellorjust( hello'hellorjust( hello'helloworldrjust( |
2,626 | helloworld'helloljust( 'hello 'hellorjust( says that we want to right-justify 'helloin string of total length 'hellois five charactersso five spaces will be added to its leftgiving us string of characters with 'hellojustified right an optional second argument to rjust(and ljust(will specify fill character other than space character enter the following into the interactive shell'hellorjust( '*''***************hello'helloljust( '-''hellothe center(string method works like ljust(and rjust(but centers the text rather than justifying it to the left or right enter the following into the interactive shell'hellocenter( hello 'hellocenter( '=''=======hello========these methods are especially useful when you need to print tabular data that has correct spacing open new file editor window and enter the following codesaving it as picnictable pydef printpicnic(itemsdictleftwidthrightwidth)print('picnic itemscenter(leftwidth rightwidth'-')for kv in itemsdict items()print( ljust(leftwidth'str(vrjust(rightwidth)picnicitems {'sandwiches' 'apples' 'cups' 'cookies' printpicnic(picnicitems printpicnic(picnicitems you can view the execution of this program at /picnictablein this programwe define printpicnic(method that will take in dictionary of information and use center()ljust()and rjust(to display that information in neatly aligned table-like format the dictionary that we'll pass to printpicnic(is picnicitems in picnicitemswe have sandwiches apples cupsand , cookies we want to organize this information into two columnswith the name of the item on the left and the quantity on the right to do thiswe decide how wide we want the left and right columns to be along with our dictionarywe'll pass these values to printpicnic(manipulating strings |
2,627 | column of tableand rightwidth for the right column it prints titlepicnic itemscentered above the table thenit loops through the dictionaryprinting each key-value pair on line with the key justified left and padded by periodsand the value justified right and padded by spaces after defining printpicnic()we define the dictionary picnicitems and call printpicnic(twicepassing it different widths for the left and right table columns when you run this programthe picnic items are displayed twice the first time the left column is characters wideand the right column is characters wide the second time they are and characters widerespectively ---picnic items-sandwiches apples cups cookies picnic itemssandwiches apples cups cookies using rjust()ljust()and center(lets you ensure that strings are neatly alignedeven if you aren' sure how many characters long your strings are removing whitespace with the strip()rstrip()and lstrip(methods sometimes you may want to strip off whitespace characters (spacetaband newlinefrom the left sideright sideor both sides of string the strip(string method will return new string without any whitespace characters at the beginning or end the lstrip(and rstrip(methods will remove whitespace characters from the left and right endsrespectively enter the following into the interactive shellspam helloworld spam strip('helloworldspam lstrip('helloworld spam rstrip(helloworldoptionallya string argument will specify which characters on the ends should be stripped enter the following into the interactive shellspam 'spamspambaconspameggsspamspamspam strip('amps''baconspameggs |
2,628 | ampand capital from the ends of the string stored in spam the order of the characters in the string passed to strip(does not matterstrip('amps'will do the same thing as strip('maps'or strip('spam'numeric values of characters with the ord(and chr(functions computers store information as bytes--strings of binary numberswhich means we need to be able to convert text to numbers because of thisevery text character has corresponding numeric value called unicode code point for examplethe numeric code point is for ' ' for ' 'and for '!you can use the ord(function to get the code point of one-character stringand the chr(function to get the one-character string of an integer code point enter the following into the interactive shellord(' ' ord(' ' ord('!' chr( 'athese functions are useful when you need to do an ordering or mathematical operation on charactersord(' ' ord(' 'ord(' 'true chr(ord(' ')'achr(ord(' ' 'bthere is more to unicode and code pointsbut those details are beyond the scope of this book if you' like to know morei recommend watching ned batchelder' pycon talk"pragmatic unicodeorhow do stop the pain?at copying and pasting strings with the pyperclip module the pyperclip module has copy(and paste(functions that can send text to and receive text from your computer' clipboard sending the output of your program to the clipboard will make it easy to paste it into an emailword processoror some other software manipulating strings |
2,629 | so faryou've been running your python scripts using the interactive shell and file editor in mu howeveryou won' want to go through the inconvenience of opening mu and the python script each time you want to run script fortunatelythere are shortcuts you can set up to make running python scripts easier the steps are slightly different for windowsmacosand linuxbut each is described in appendix turn to appendix to learn how to run your python scripts conveniently and be able to pass command line arguments to them (you will not be able to pass command line arguments to your programs using mu the pyperclip module does not come with python to install itfollow the directions for installing third-party modules in appendix after installing pyperclipenter the following into the interactive shellimport pyperclip pyperclip copy('helloworld!'pyperclip paste('helloworld!of courseif something outside of your program changes the clipboard contentsthe paste(function will return it for exampleif copied this sentence to the clipboard and then called paste()it would look like thispyperclip paste('for exampleif copied this sentence to the clipboard and then called paste()it would look like this:projectmulti-clipboard automatic messages if you've responded to large number of emails with similar phrasingyou've probably had to do lot of repetitive typing maybe you keep text document with these phrases so you can easily copy and paste them using the clipboard but your clipboard can only store one message at timewhich isn' very convenient let' make this process bit easier with program that stores multiple phrases step program design and data structures you want to be able to run this program with command line argument that is short key phrase--for instanceagree or busy the message associated with that key phrase will be copied to the clipboard so that the user can paste it into an email this waythe user can have longdetailed messages without having to retype them |
2,630 | this is the first "projectof the book from here oneach will have projects that demonstrate the concepts covered in the the projects are written in style that takes you from blank file editor window to fullworking program just like with the interactive shell examplesdon' only read the project sections--follow along on your computeropen new file editor window and save the program as mclip py you need to start the program with #(shebangline (see appendix band should also write comment that briefly describes the program since you want to associate each piece of text with its key phraseyou can store these as strings in dictionary the dictionary will be the data structure that organizes your key phrases and text make your program look like the following#python mclip py multi-clipboard program text {'agree'"""yesi agree that sounds fine to me """'busy'"""sorrycan we do this later this week or next week?"""'upsell'"""would you consider making this monthly donation?"""step handle command line arguments the command line arguments will be stored in the variable sys argv (see appendix for more information on how to use command line arguments in your programs the first item in the sys argv list should always be string containing the program' filename ('mclip py')and the second item should be the first command line argument for this programthis argument is the key phrase of the message you want since the command line argument is mandatoryyou display usage message to the user if they forget to add it (that isif the sys argv list has fewer than two values in itmake your program look like the following#python mclip py multi-clipboard program text {'agree'"""yesi agree that sounds fine to me """'busy'"""sorrycan we do this later this week or next week?"""'upsell'"""would you consider making this monthly donation?"""import sys if len(sys argv print('usagepython mclip py [keyphrasecopy phrase text'sys exit(keyphrase sys argv[ first command line arg is the keyphrase manipulating strings |
2,631 | now that the key phrase is stored as string in the variable keyphraseyou need to see whether it exists in the text dictionary as key if soyou want to copy the key' value to the clipboard using pyperclip copy((since you're using the pyperclip moduleyou need to import it note that you don' actually need the keyphrase variableyou could just use sys argv[ everywhere keyphrase is used in this program but variable named keyphrase is much more readable than something cryptic like sys argv[ make your program look like the following#python mclip py multi-clipboard program text {'agree'"""yesi agree that sounds fine to me """'busy'"""sorrycan we do this later this week or next week?"""'upsell'"""would you consider making this monthly donation?"""import syspyperclip if len(sys argv print('usagepy mclip py [keyphrasecopy phrase text'sys exit(keyphrase sys argv[ first command line arg is the keyphrase if keyphrase in textpyperclip copy(text[keyphrase]print('text for keyphrase copied to clipboard 'elseprint('there is no text for keyphrasethis new code looks in the text dictionary for the key phrase if the key phrase is key in the dictionarywe get the value corresponding to that keycopy it to the clipboardand print message saying that we copied the value otherwisewe print message saying there' no key phrase with that name that' the complete script using the instructions in appendix for launching command line programs easilyyou now have fast way to copy messages to the clipboard you will have to modify the text dictionary value in the source whenever you want to update the program with new message on windowsyou can create batch file to run this program with the win- run window (for more about batch filessee appendix enter the following into the file editor and save the file as mclip bat in the :\windows folder@py exe :\path_to_file\mclip py %@pause with this batch file createdrunning the multi-clipboard program on windows is just matter of pressing win- and typing mclip key phrase |
2,632 | when editing wikipedia articleyou can create bulleted list by putting each list item on its own line and placing star in front but say you have really large list that you want to add bullet points to you could just type those stars at the beginning of each lineone by one or you could automate this task with short python script the bulletpointadder py script will get the text from the clipboardadd star and space to the beginning of each lineand then paste this new text to the clipboard for exampleif copied the following text (for the wikipedia article "list of lists of lists"to the clipboardlists of animals lists of aquarium life lists of biologists by author abbreviation lists of cultivars and then ran the bulletpointadder py programthe clipboard would then contain the followinglists of animals lists of aquarium life lists of biologists by author abbreviation lists of cultivars this star-prefixed text is ready to be pasted into wikipedia article as bulleted list step copy and paste from the clipboard you want the bulletpointadder py program to do the following paste text from the clipboard do something to it copy the new text to the clipboard that second step is little trickybut steps and are pretty straightforwardthey just involve the pyperclip copy(and pyperclip paste(functions for nowlet' just write the part of the program that covers steps and enter the followingsaving the program as bulletpointadder py#python bulletpointadder py adds wikipedia bullet points to the start of each line of text on the clipboard import pyperclip text pyperclip paste(todoseparate lines and add stars pyperclip copy(textmanipulating strings |
2,633 | the program eventually the next step is to actually implement that piece of the program step separate the lines of text and add the star the call to pyperclip paste(returns all the text on the clipboard as one big string if we used the "list of lists of listsexamplethe string stored in text would look like this'lists of animals\nlists of aquarium life\nlists of biologists by author abbreviation\nlists of cultivarsthe \ newline characters in this string cause it to be displayed with multiple lines when it is printed or pasted from the clipboard there are many "linesin this one string value you want to add star to the start of each of these lines you could write code that searches for each \ newline character in the string and then adds the star just after that but it would be easier to use the split(method to return list of stringsone for each line in the original stringand then add the star to the front of each string in the list make your program look like the following#python bulletpointadder py adds wikipedia bullet points to the start of each line of text on the clipboard import pyperclip text pyperclip paste(separate lines and add stars lines text split('\ 'for in range(len(lines))loop through all indexes in the "lineslist lines[ 'lines[iadd star to each string in "lineslist pyperclip copy(textwe split the text along its newlines to get list in which each item is one line of the text we store the list in lines and then loop through the items in lines for each linewe add star and space to the start of the line now each string in lines begins with star step join the modified lines the lines list now contains modified lines that start with stars but pyperclip copy(is expecting single string valuehowevernot list of string values to make this single string valuepass lines into the join(method to get single string joined from the list' strings make your program look like the following#python bulletpointadder py adds wikipedia bullet points to the start |
2,634 | import pyperclip text pyperclip paste(separate lines and add stars lines text split('\ 'for in range(len(lines))loop through all indexes for "lineslist lines[ 'lines[iadd star to each string in "lineslist text '\njoin(linespyperclip copy(textwhen this program is runit replaces the text on the clipboard with text that has stars at the start of each line now the program is completeand you can try running it with text copied to the clipboard even if you don' need to automate this specific taskyou might want to automate some other kind of text manipulationsuch as removing trailing spaces from the end of lines or converting text to uppercase or lowercase whatever your needsyou can use the clipboard for input and output short progampig latin pig latin is silly made-up language that alters english words if word begins with vowelthe word yay is added to the end of it if word begins with consonant or consonant cluster (like ch or gr)that consonant or cluster is moved to the end of the word followed by ay let' write pig latin program that will output something like thisenter the english message to translate into pig latinmy name is al sweigart and am , years old ymay amenay isyay alyay eigartsway andyay iyay amyay , yearsyay oldyay this program works by altering string using the methods introduced in this type the following source code into the file editorand save the file as piglat pyenglish to pig latin print('enter the english message to translate into pig latin:'message input(vowels (' '' '' '' '' '' 'piglatin [ list of the words in pig latin for word in message split()separate the non-letters at the start of this wordprefixnonletters 'while len(word and not word[ isalpha()prefixnonletters +word[ word word[ :manipulating strings |
2,635 | piglatin append(prefixnonletterscontinue separate the non-letters at the end of this wordsuffixnonletters 'while not word[- isalpha()suffixnonletters +word[- word word[:- remember if the word was in uppercase or title case wasupper word isupper(wastitle word istitle(word word lower(make the word lowercase for translation separate the consonants at the start of this wordprefixconsonants 'while len(word and not word[ in vowelsprefixconsonants +word[ word word[ :add the pig latin ending to the wordif prefixconsonants !''word +prefixconsonants 'ayelseword +'yayset the word back to uppercase or title caseif wasupperword word upper(if wastitleword word title(add the non-letters back to the start or end of the word piglatin append(prefixnonletters word suffixnonlettersjoin all the words back together into single stringprint(join(piglatin)let' look at this code line by linestarting at the topenglish to pig latin print('enter the english message to translate into pig latin:'message input(vowels (' '' '' '' '' '' 'firstwe ask the user to enter the english text to translate into pig latin alsowe create constant that holds every lowercase vowel letter (and yas tuple of strings this will be used later in our program |
2,636 | translate them into pig latinpiglatin [ list of the words in pig latin for word in message split()separate the non-letters at the start of this wordprefixnonletters 'while len(word and not word[ isalpha()prefixnonletters +word[ word word[ :if len(word= piglatin append(prefixnonletterscontinue we need each word to be its own stringso we call message split(to get list of the words as separate strings the string 'my name is al sweigart and am , years old would cause split(to return ['my''name''is''al''sweigart''and'' ''am'' , ''years''old 'we need to remove any non-letters from the start and end of each word so that strings like 'old translate to 'oldyay instead of 'old yaywe'll save these non-letters to variable named prefixnonletters separate the non-letters at the end of this wordsuffixnonletters 'while not word[- isalpha()suffixnonletters +word[- word word[:- loop that calls isalpha(on the first character in the word will determine if we should remove character from word and concatenate it to the end of prefixnonletters if the entire word is made of non-letter characterslike ' , 'we can simply append it to the piglatin list and continue to the next word to translate we also need to save the non-letters at the end of the word string this code is similar to the previous loop nextwe'll make sure the program remembers if the word was in uppercase or title case so we can restore it after translating the word to pig latinremember if the word was in uppercase or title case wasupper word isupper(wastitle word istitle(word word lower(make the word lowercase for translation for the rest of the code in the for loopwe'll work on lowercase version of word manipulating strings |
2,637 | the consonants from the beginning of wordseparate the consonants at the start of this wordprefixconsonants 'while len(word and not word[ in vowelsprefixconsonants +word[ word word[ :we use loop similar to the loop that removed the non-letters from the start of wordexcept now we are pulling off consonants and storing them to variable named prefixconsonants if there were any consonants at the start of the wordthey are now in prefixconsonants and we should concatenate that variable and the string 'ayto the end of word otherwisewe can assume word begins with vowel and we only need to concatenate 'yay'add the pig latin ending to the wordif prefixconsonants !''word +prefixconsonants 'ayelseword +'yayrecall that we set word to its lowercase version with word word lower(if word was originally in uppercase or title casethis code will convert word back to its original caseset the word back to uppercase or title caseif wasupperword word upper(if wastitleword word title(at the end of the for loopwe append the wordalong with any nonletter prefix or suffix it originally hadto the piglatin listadd the non-letters back to the start or end of the word piglatin append(prefixnonletters word suffixnonlettersjoin all the words back together into single stringprint(join(piglatin)after this loop finisheswe combine the list of strings into single string by calling the join(method this single string is passed to print(to display our pig latin on the screen you can find other shorttext-based python programs like this one at |
2,638 | text is common form of dataand python comes with many helpful string methods to process the text stored in string values you will make use of indexingslicingand string methods in almost every python program you write the programs you are writing now don' seem too sophisticated-they don' have graphical user interfaces with images and colorful text so faryou're displaying text with print(and letting the user enter text with input(howeverthe user can quickly enter large amounts of text through the clipboard this ability provides useful avenue for writing programs that manipulate massive amounts of text these text-based programs might not have flashy windows or graphicsbut they can get lot of useful work done quickly another way to manipulate large amounts of text is reading and writing files directly off the hard drive you'll learn how to do this with python in that just about covers all the basic concepts of python programmingyou'll continue to learn new concepts throughout the rest of this bookbut you now know enough to start writing some useful programs that can automate tasks if you' like to see collection of shortsimple python programs built from the basic concepts you've learned so farcheck out github com/asweigart/pythonstdiogamestry copying the source code for each program by handand then make modifications to see how they affect the behavior of the program once you have an understanding of how the program workstry re-creating the program yourself from scratch you don' need to re-create the source code exactlyjust focus on what the program does rather than how it does it you might not think you have enough python knowledge to do things such as download web pagesupdate spreadsheetsor send text messagesbut that' where python modules come inthese moduleswritten by other programmersprovide functions that make it easy for you to do all these things so let' learn how to write real programs to do useful automated tasks practice questions what are escape characterswhat do the \ and \ escape characters representhow can you put backslash character in stringthe string value "howl' moving castleis valid string why isn' it problem that the single quote character in the word howl' isn' escapedif you don' want to put \ in your stringhow can you write string with newlines in itmanipulating strings |
2,639 | what do the following expressions evaluate to'helloworld!'[ 'helloworld!'[ : 'helloworld!'[: 'helloworld!'[ :what do the following expressions evaluate to'helloupper('helloupper(isupper('helloupper(lower( what do the following expressions evaluate to'rememberrememberthe fifth of november split('-join('there can be only one split() what string methods can you use to right-justifyleft-justifyand center string how can you trim whitespace characters from the beginning or end of stringpractice projects for practicewrite programs that do the following table printer write function named printtable(that takes list of lists of strings and displays it in well-organized table with each column right-justified assume that all the inner lists will contain the same number of strings for examplethe value could look like thistabledata [['apples''oranges''cherries''banana']['alice''bob''carol''david']['dogs''cats''moose''goose']your printtable(function would print the followingapples alice dogs oranges bob cats cherries carol moose banana david goose hintyour code will first have to find the longest string in each of the inner lists so that the whole column can be wide enough to fit all the strings you can store the maximum width of each column as list of integers the printtable(function can begin with colwidths [ len(tabledata)which will create list containing the same number of values as the number of inner lists in tabledata that waycolwidths[ can store the width of the |
2,640 | the colwidths list to find out what integer width to pass to the rjust(string method zombie dice bots programming games are game genre where instead of playing game directlyplayers write bot programs to play the game autonomously 've created zombie dice simulatorwhich allows programmers to practice their skills while making game-playing ais zombie dice bots can be simple or incredibly complexand are great for class exercise or an individual programming challenge zombie dice is quickfun dice game from steve jackson games the players are zombies trying to eat as many human brains as possible without getting shot three times there is cup of dice with brainsfootstepsand shotgun icons on their faces the dice icons are coloredand each color has different likelihood of each event occurring every die has two sides with footstepsbut dice with green icons have more sides with brainsred-icon dice have more shotgunsand yellow-icon dice have an even split of brains and shotguns do the following on each player' turn place all dice in the cup the player randomly draws three dice from the cup and then rolls them players always roll exactly three dice they set aside and count up any brains (humans whose brains were eatenand shotguns (humans who fought backaccumulating three shotguns automatically ends player' turn with zero points (regardless of how many brains they hadif they have between zero and two shotgunsthey may continue rolling if they want they may also choose to end their turn and collect one point per brain if the player decides to keep rollingthey must reroll all dice with footsteps remember that the player must always roll three dicethey must draw more dice out of the cup if they have fewer than three footsteps to roll player may keep rolling dice until either they get three shotguns--losing everything--or all dice have been rolled player may not reroll only one or two diceand may not stop mid-reroll when someone reaches brainsthe rest of the players finish out the round the person with the most brains wins if there' tiethe tied players play one last tiebreaker round zombie dice has push-your-luck game mechanicthe more you reroll the dicethe more brains you can getbut the more likely you'll eventually accrue three shotguns and lose everything once player reaches pointsthe rest of the players get one more turn (to potentially catch upand the game ends the player with the most points wins you can find the complete rules at manipulating strings |
2,641 | appendix you can run demo of the simulator with some pre-made bots by running the following in the interactive shellimport zombiedice zombiedice demo(zombie dice visualization is running open your browser to localhost: to view it press ctrl- to quit the program launches your web browserwhich will look like figure - figure - the web gui for the zombie dice simulator you'll create bots by writing class with turn(methodwhich is called by the simulator when it' your bot' turn to roll the dice classes are beyond the scope of this bookso the class code is already set up for you in the myzombie py programwhich is in the downloadable zip file for this book at myzombie py program as template inside this turn(methodyou'll call the zombiedice roll(function as often as you want your bot to roll the dice import zombiedice class myzombiedef __init__(selfname)all zombies must have nameself name name def turn(selfgamestate) |
2,642 | you can choose to ignore it in your code dicerollresults zombiedice roll(first roll roll(returns dictionary with keys 'brains''shotgun'and 'footstepswith how many rolls of each type there were the 'rollskey is list of (coloricontuples with the exact roll result information example of roll(return value{'brains' 'footsteps' 'shotgun' 'rolls'[('yellow''brains')('red''footsteps')('green''shotgun')]replace this zombie code with your ownbrains while dicerollresults is not nonebrains +dicerollresults['brains'if brains dicerollresults zombiedice roll(roll again elsebreak zombies zombiedice examples randomcoinflipzombie(name='random')zombiedice examples rollsuntilintheleadzombie(name='until leading')zombiedice examples minnumshotgunsthenstopszombie(name='stop at shotguns'minshotguns= )zombiedice examples minnumshotgunsthenstopszombie(name='stop at shotgun'minshotguns= )myzombie(name='my zombie bot')add any other zombie players here uncomment one of the following lines to run in cli or web gui mode#zombiedice runtournament(zombies=zombiesnumgames= zombiedice runwebgui(zombies=zombiesnumgames= the turn(method takes two parametersself and gamestate you can ignore these in your first few zombie bots and consult the online documentation for details later if you want to learn more the turn(method should call zombiedice roll(at least once for the initial roll thendepending on the strategy the bot usesit can call zombiedice roll(again as many times as it wants in myzombie pythe turn(method calls zombiedice roll(twicewhich means the zombie bot will always roll its dice two times per turn regardless of the results of the roll the return value of zombiedice roll(tells your code the results of the dice roll it is dictionary with four keys three of the keys'shotgun''brains'and 'footsteps'have integer values of how many dice came up with those icons the fourth 'rollskey has value that is list of tuples for each die roll the tuples contain two stringsthe color of the die at index and the icon rolled at index look at the code comments in the turn(manipulating strings |
2,643 | try writing some of your own bots to play zombie dice and see how they compare against the other bots specificallytry to create the following botsa bot thatafter the first rollrandomly decides if it will continue or stop bot that stops rolling after it has rolled two brains bot that stops rolling after it has rolled two shotguns bot that initially decides it'll roll the dice one to four timesbut will stop early if it rolls two shotguns bot that stops rolling after it has rolled more shotguns than brains run these bots through the simulator and see how they compare to each other you can also examine the code of some premade bots at in the real worldyou'll have the benefit of thousands of simulated games telling you that one of the best strategies is to simply stop once you've rolled two shotguns but you could always try pressing your luck |
2,644 | au tom at ing ta sks |
2,645 | pat atching regul ar xpressions you may be familiar with searching for text by pressing ctrl- and entering the words you're looking for regular expressions go one step furtherthey allow you to specify pattern of text to search for you may not know business' exact phone numberbut if you live in the united states or canadayou know it will be three digitsfollowed by hyphenand then four more digits (and optionallya three-digit area code at the startthis is how youas humanknow phone number when you see it - is phone numberbut , , , is not we also recognize all sorts of other text patterns every dayemail addresses have symbols in the middleus social security numbers have nine digits and two hyphenswebsite urls often have periods and forward slashesnews headlines use title casesocial media hashtags begin with and contain no spacesand more |
2,646 | them even though most modern text editors and word processorssuch as microsoft word or openofficehave find and find-and-replace features that can search based on regular expressions regular expressions are huge time-saversnot just for software users but also for programmers in facttech writer cory doctorow argues that we should be teaching regular expressions even before programmingknowing [regular expressionscan mean the difference between solving problem in steps and solving it in , steps when you're nerdyou forget that the problems you solve with couple keystrokes can take other people days of tediouserror-prone work to slog through in this you'll start by writing program to find text patterns without using regular expressions and then see how to use regular expressions to make the code much less bloated 'll show you basic matching with regular expressions and then move on to some more powerful featuressuch as string substitution and creating your own character classes finallyat the end of the you'll write program that can automatically extract phone numbers and email addresses from block of text finding patterns of text without regular expressions say you want to find an american phone number in string you know the pattern if you're americanthree numbersa hyphenthree numbersa hyphenand four numbers here' an examplelet' use function named isphonenumber(to check whether string matches this patternreturning either true or false open new file editor tab and enter the following codethen save the file as isphonenumber pydef isphonenumber(text)if len(text! return false for in range( )if not text[iisdecimal()return false if text[ !'-'return false for in range( )if not text[iisdecimal()return false if text[ !'-'return false cory doctorow"here' what ict should really teach kidshow to do regular expressions,guardiandecember /dec/ /ict-teach-kids-regular-expressions |
2,647 | if not text[iisdecimal()return false return true print('is phone number?'print(isphonenumber('')print('is moshi moshi phone number?'print(isphonenumber('moshi moshi')when this program is runthe output looks like thisis phone numbertrue is moshi moshi phone numberfalse the isphonenumber(function has code that does several checks to see whether the string in text is valid phone number if any of these checks failthe function returns false first the code checks that the string is exactly characters then it checks that the area code (that isthe first three characters in textconsists of only numeric characters the rest of the function checks that the string follows the pattern of phone numberthe number must have the first hyphen after the area code three more numeric characters then another hyphen and finally four more numbers if the program execution manages to get past all the checksit returns true calling isphonenumber(with the argument 'will return true calling isphonenumber(with 'moshi moshiwill return falsethe first test fails because 'moshi moshiis not characters long if you wanted to find phone number within larger stringyou would have to add even more code to find the phone number pattern replace the last four print(function calls in isphonenumber py with the followingmessage 'call me at tomorrow is my office for in range(len(message))chunk message[ : + if isphonenumber(chunk)print('phone number foundchunkprint('done'when this program is runthe output will look like thisphone number foundphone number founddone pattern matching with regular expressions |
2,648 | message is assigned to the variable chunk for exampleon the first iterationi is and chunk is assigned message[ : (that isthe string 'call me at 'on the next iterationi is and chunk is assigned message[ : (the string 'all me at 'in other wordson each iteration of the for loopchunk takes on the following values'call me at 'll me at 'all me at ' me at -and so on you pass chunk to isphonenumber(to see whether it matches the phone number pattern and if soyou print the chunk continue to loop through messageand eventually the characters in chunk will be phone number the loop goes through the entire stringtesting each -character piece and printing any chunk it finds that satisfies isphonenumber(once we're done going through messagewe print done while the string in message is short in this exampleit could be millions of characters long and the program would still run in less than second similar program that finds phone numbers using regular expressions would also run in less than secondbut regular expressions make it quicker to write these programs finding patterns of text with regular expressions the previous phone number-finding program worksbut it uses lot of code to do something limitedthe isphonenumber(function is lines but can find only one pattern of phone numbers what about phone number formatted like or ( - what if the phone number had an extensionlike the isphonenumber(function would fail to validate them you could add yet more code for these additional patternsbut there is an easier way regular expressionscalled regexes for shortare descriptions for pattern of text for examplea \ in regex stands for digit character--that isany single numeral from to the regex \ \ \ -\ \ \ -\ \ \ \ is used by python to match the same text pattern the previous isphonenumber(function dida string of three numbersa hyphenthree more numbersanother hyphenand four numbers any other string would not match the \ \ \ -\ \ \ -\ \ \ \ regex but regular expressions can be much more sophisticated for exampleadding in braces ({ }after pattern is like saying"match this pattern three times so the slightly shorter regex \ { }-\ { }-\ { also matches the correct phone number format |
2,649 | all the regex functions in python are in the re module enter the following into the interactive shell to import this moduleimport re note most of the examples in this will require the re moduleso remember to import it at the beginning of any script you write or any time you restart mu otherwiseyou'll get nameerrorname 'reis not defined error message passing string value representing your regular expression to re compile(returns regex pattern object (or simplya regex objectto create regex object that matches the phone number patternenter the following into the interactive shell (remember that \ means " digit characterand \ \ \ -\ \ \ -\ \ \ \ is the regular expression for phone number pattern phonenumregex re compile( '\ \ \ -\ \ \ -\ \ \ \ 'now the phonenumregex variable contains regex object matching regex objects regex object' search(method searches the string it is passed for any matches to the regex the search(method will return none if the regex pattern is not found in the string if the pattern is foundthe search(method returns match objectwhich have group(method that will return the actual matched text from the searched string ( 'll explain groups shortly for exampleenter the following into the interactive shellphonenumregex re compile( '\ \ \ -\ \ \ -\ \ \ \ 'mo phonenumregex search('my number is 'print('phone number foundmo group()phone number foundthe mo variable name is just generic name to use for match objects this example might seem complicated at firstbut it is much shorter than the earlier isphonenumber py program and does the same thing herewe pass our desired pattern to re compile(and store the resulting regex object in phonenumregex then we call search(on phonenumregex and pass search(the string we want to match for during the search the result of the search gets stored in the variable mo in this examplewe know that our pattern will be found in the stringso we know that match object will be returned knowing that mo contains match object and not the null value nonewe can call group(on mo to return the match writing mo group(inside our print(function call displays the whole matchpattern matching with regular expressions |
2,650 | while there are several steps to using regular expressions in pythoneach step is fairly simple note import the regex module with import re create regex object with the re compile(function (remember to use raw string pass the string you want to search into the regex object' search(method this returns match object call the match object' group(method to return string of the actual matched text while encourage you to enter the example code into the interactive shellyou should also make use of web-based regular expression testerswhich can show you exactly how regex matches piece of text that you enter recommend the tester at more pattern matching with regular expressions now that you know the basic steps for creating and finding regular expression objects using pythonyou're ready to try some of their more powerful pattern-matching capabilities grouping with parentheses say you want to separate the area code from the rest of the phone number adding parentheses will create groups in the regex(\ \ \ )-(\ \ \ -\ \dd\dthen you can use the group(match object method to grab the matching text from just one group the first set of parentheses in regex string will be group the second set will be group by passing the integer or to the group(match object methodyou can grab different parts of the matched text passing or nothing to the group(method will return the entire matched text enter the following into the interactive shellphonenumregex re compile( '(\ \ \ )-(\ \ \ -\ \ \ \ )'mo phonenumregex search('my number is 'mo group( ' mo group( ' - mo group( 'mo group('if you would like to retrieve all the groups at onceuse the groups(method--note the plural form for the name |
2,651 | (' '' - 'areacodemainnumber mo groups(print(areacode print(mainnumber - since mo groups(returns tuple of multiple valuesyou can use the multiple-assignment trick to assign each value to separate variableas in the previous areacodemainnumber mo groups(line parentheses have special meaning in regular expressionsbut what do you do if you need to match parenthesis in your textfor instancemaybe the phone numbers you are trying to match have the area code set in parentheses in this caseyou need to escape the and characters with backslash enter the following into the interactive shellphonenumregex re compile( '(\(\ \ \ \)(\ \ \ -\ \ \ \ )'mo phonenumregex search('my phone number is ( - 'mo group( '( )mo group( ' - the \and \escape characters in the raw string passed to re compile(will match actual parenthesis characters in regular expressionsthe following characters have special meaningsif you want to detect these characters as part of your text patternyou need to escape them with backslash\\\\\\\\\\\\\make sure to double-check that you haven' mistaken escaped parentheses \and \for parentheses and in regular expression if you receive an error message about "missing )or "unbalanced parenthesis,you may have forgotten to include the closing unescaped parenthesis for grouplike in this examplere compile( '(\(parentheses\)'traceback (most recent call last)--snip-re errormissing )unterminated subpattern at position the error message tells you that there is an opening parenthesis at index of the '(\(parentheses\)string that is missing its corresponding closing parenthesis pattern matching with regular expressions |
2,652 | the character is called pipe you can use it anywhere you want to match one of many expressions for examplethe regular expression 'batman|tina feywill match either 'batmanor 'tina feywhen both batman and tina fey occur in the searched stringthe first occurrence of matching text will be returned as the match object enter the following into the interactive shellheroregex re compile ( 'batman|tina fey'mo heroregex search('batman and tina fey'mo group('batmanmo heroregex search('tina fey and batman'mo group('tina feynote you can find all matching occurrences with the findall(method that' discussed in "the findall(methodon page you can also use the pipe to match one of several patterns as part of your regex for examplesay you wanted to match any of the strings 'batman''batmobile''batcopter'and 'batbatsince all these strings start with batit would be nice if you could specify that prefix only once this can be done with parentheses enter the following into the interactive shellbatregex re compile( 'bat(man|mobile|copter|bat)'mo batregex search('batmobile lost wheel'mo group('batmobilemo group( 'mobilethe method call mo group(returns the full matched text 'batmobile'while mo group( returns just the part of the matched text inside the first parentheses group'mobileby using the pipe character and grouping parenthesesyou can specify several alternative patterns you would like your regex to match if you need to match an actual pipe characterescape it with backslashlike \optional matching with the question mark sometimes there is pattern that you want to match only optionally that isthe regex should find match regardless of whether that bit of text is there the character flags the group that precedes it as an optional part of the pattern for exampleenter the following into the interactive shellbatregex re compile( 'bat(wo)?man'mo batregex search('the adventures of batman' |
2,653 | 'batmanmo batregex search('the adventures of batwoman'mo group('batwomanthe (wo)part of the regular expression means that the pattern wo is an optional group the regex will match text that has zero instances or one instance of wo in it this is why the regex matches both 'batwomanand 'batmanusing the earlier phone number exampleyou can make the regex look for phone numbers that do or do not have an area code enter the following into the interactive shellphoneregex re compile( '(\ \ \ -)?\ \ \ -\ \ \ \ 'mo phoneregex search('my number is 'mo group('mo phoneregex search('my number is - 'mo group(' - you can think of the as saying"match zero or one of the group preceding this question mark if you need to match an actual question mark characterescape it with \matching zero or more with the star the (called the star or asteriskmeans "match zero or more"--the group that precedes the star can occur any number of times in the text it can be completely absent or repeated over and over again let' look at the batman example again batregex re compile( 'bat(wo)*man'mo batregex search('the adventures of batman'mo group('batmanmo batregex search('the adventures of batwoman'mo group('batwomanmo batregex search('the adventures of batwowowowoman'mo group('batwowowowomanfor 'batman'the (wo)part of the regex matches zero instances of wo in the stringfor 'batwoman'the (wo)matches one instance of woand for 'batwowowowoman'(wo)matches four instances of wo if you need to match an actual star characterprefix the star in the regular expression with backslash\pattern matching with regular expressions |
2,654 | while means "match zero or more,the (or plusmeans "match one or more unlike the starwhich does not require its group to appear in the matched stringthe group preceding plus must appear at least once it is not optional enter the following into the interactive shelland compare it with the star regexes in the previous sectionbatregex re compile( 'bat(wo)+man'mo batregex search('the adventures of batwoman'mo group('batwomanmo batregex search('the adventures of batwowowowoman'mo group('batwowowowomanmo batregex search('the adventures of batman'mo =none true the regex bat(wo)+man will not match the string 'the adventures of batman'because at least one wo is required by the plus sign if you need to match an actual plus sign characterprefix the plus sign with backslash to escape it\matching specific repetitions with braces if you have group that you want to repeat specific number of timesfollow the group in your regex with number in braces for examplethe regex (ha){ will match the string 'hahaha'but it will not match 'haha'since the latter has only two repeats of the (hagroup instead of one numberyou can specify range by writing minimuma commaand maximum in between the braces for examplethe regex (ha){ , will match 'hahaha''hahahaha'and 'hahahahahayou can also leave out the first or second number in the braces to leave the minimum or maximum unbounded for example(ha){ ,will match three or more instances of the (hagroupwhile (ha){, will match zero to five instances braces can help make your regular expressions shorter these two regular expressions match identical patterns(ha){ (ha)(ha)(haand these two regular expressions also match identical patterns(ha){ , ((ha)(ha)(ha))|((ha)(ha)(ha)(ha))|((ha)(ha)(ha)(ha)(ha) |
2,655 | haregex re compile( '(ha){ }'mo haregex search('hahaha'mo group('hahahamo haregex search('ha'mo =none true here(ha){ matches 'hahahabut not 'hasince it doesn' match 'ha'search(returns none greedy and non-greedy matching since (ha){ , can match threefouror five instances of ha in the string 'hahahahaha'you may wonder why the match object' call to group(in the previous brace example returns 'hahahahahainstead of the shorter possibilities after all'hahahaand 'hahahahaare also valid matches of the regular expression (ha){ , python' regular expressions are greedy by defaultwhich means that in ambiguous situations they will match the longest string possible the nongreedy (also called lazyversion of the braceswhich matches the shortest string possiblehas the closing brace followed by question mark enter the following into the interactive shelland notice the difference between the greedy and non-greedy forms of the braces searching the same stringgreedyharegex re compile( '(ha){ , }'mo greedyharegex search('hahahahaha'mo group('hahahahahanongreedyharegex re compile( '(ha){ , }?'mo nongreedyharegex search('hahahahaha'mo group('hahahanote that the question mark can have two meanings in regular expressionsdeclaring non-greedy match or flagging an optional group these meanings are entirely unrelated the findall(method in addition to the search(methodregex objects also have findall(method while search(will return match object of the first matched text in the searched stringthe findall(method will return the strings of every pattern matching with regular expressions |
2,656 | only on the first instance of matching textenter the following into the interactive shellphonenumregex re compile( '\ \ \ -\ \ \ -\ \ \ \ 'mo phonenumregex search('cellwork'mo group('on the other handfindall(will not return match object but list of strings--as long as there are no groups in the regular expression each string in the list is piece of the searched text that matched the regular expression enter the following into the interactive shellphonenumregex re compile( '\ \ \ -\ \ \ -\ \ \ \ 'has no groups phonenumregex findall('cellwork'[''''if there are groups in the regular expressionthen findall(will return list of tuples each tuple represents found matchand its items are the matched strings for each group in the regex to see findall(in actionenter the following into the interactive shell (notice that the regular expression being compiled now has groups in parentheses)phonenumregex re compile( '(\ \ \ )-(\ \ \ )-(\ \ \ \ )'has groups phonenumregex findall('cellwork'[(' '' '' ')(' '' '' ')to summarize what the findall(method returnsremember the followingwhen called on regex with no groupssuch as \ \ \ -\ \ \ -\dd\ \dthe method findall(returns list of string matchessuch as [''''when called on regex that has groupssuch as (\ \ \ )-(\ \ \ -(\ \ \ \ )the method findall(returns list of tuples of strings (one string for each group)such as [(' '' '' ')(' '' '' ')character classes in the earlier phone number regex exampleyou learned that \ could stand for any numeric digit that is\ is shorthand for the regular expression ( | | | | | | | | | there are many such shorthand character classesas shown in table - |
2,657 | shorthand character class represents \ any numeric digit from to \ any character that is not numeric digit from to \ any letternumeric digitor the underscore character (think of this as matching "wordcharacters \ any character that is not letternumeric digitor the underscore character \ any spacetabor newline character (think of this as matching "spacecharacters \ any character that is not spacetabor newline character classes are nice for shortening regular expressions the character class [ - will match only the numbers to this is much shorter than typing ( | | | | | note that while \ matches digits and \ matches digitslettersand the underscorethere is no shorthand character class that matches only letters (though you can use the [ -za-zcharacter classas explained next for exampleenter the following into the interactive shellxmasregex re compile( '\ +\ \ +'xmasregex findall(' drummers pipers lords ladies maids swans geese rings birds hens doves partridge'[' drummers'' pipers'' lords'' ladies'' maids'' swans'' geese'' rings'' birds'' hens'' doves'' partridge'the regular expression \ +\ \wwill match text that has one or more numeric digits (\ +)followed by whitespace character (\ )followed by one or more letter/digit/underscore characters (\ +the findall(method returns all matching strings of the regex pattern in list making your own character classes there are times when you want to match set of characters but the shorthand character classes (\ \ \sand so onare too broad you can define your own character class using square brackets for examplethe character class [aeiouaeiouwill match any vowelboth lowercase and uppercase enter the following into the interactive shellvowelregex re compile( '[aeiouaeiou]'vowelregex findall('robocop eats baby food baby food '[' '' '' '' '' '' '' '' '' '' '' 'pattern matching with regular expressions |
2,658 | for examplethe character class [ -za- - will match all lowercase lettersuppercase lettersand numbers note that inside the square bracketsthe normal regular expression symbols are not interpreted as such this means you do not need to escape the *?or (characters with preceding backslash for examplethe character class [ - will match digits to and period you do not need to write it as [ - by placing caret character (^just after the character class' opening bracketyou can make negative character class negative character class will match all the characters that are not in the character class for exampleenter the following into the interactive shellconsonantregex re compile( '[^aeiouaeiou]'consonantregex findall('robocop eats baby food baby food '[' '' '' '' ''' '' ''' '' '' ''' '' '''' '' '' ''' '' ''nowinstead of matching every vowelwe're matching every character that isn' vowel the caret and dollar sign characters you can also use the caret symbol (^at the start of regex to indicate that match must occur at the beginning of the searched text likewiseyou can put dollar sign ($at the end of the regex to indicate the string must end with this regex pattern and you can use the and together to indicate that the entire string must match the regex--that isit' not enough for match to be made on some subset of the string for examplethe '^helloregular expression string matches strings that begin with 'helloenter the following into the interactive shellbeginswithhello re compile( '^hello'beginswithhello search('helloworld!'beginswithhello search('he said hello '=none true the '\ $regular expression string matches strings that end with numeric character from to enter the following into the interactive shellendswithnumber re compile( '\ $'endswithnumber search('your number is 'endswithnumber search('your number is forty two '=none true |
2,659 | and end with one or more numeric characters enter the following into the interactive shellwholestringisnum re compile( '^\ +$'wholestringisnum search(' 'wholestringisnum search(' xyz '=none true wholestringisnum search(' '=none true the last two search(calls in the previous interactive shell example demonstrate how the entire string must match the regex if and are used always confuse the meanings of these two symbolsso use the mnemonic "carrots cost dollarsto remind myself that the caret comes first and the dollar sign comes last the wildcard character the (or dotcharacter in regular expression is called wildcard and will match any character except for newline for exampleenter the following into the interactive shellatregex re compile(rat'atregex findall('the cat in the hat sat on the flat mat '['cat''hat''sat''lat''mat'remember that the dot character will match just one characterwhich is why the match for the text flat in the previous example matched only lat to match an actual dotescape the dot with backslashmatching everything with dot-star sometimes you will want to match everything and anything for examplesay you want to match the string 'first name:'followed by any and all textfollowed by 'last name:'and then followed by anything again you can use the dot-star *to stand in for that "anything remember that the dot character means "any single character except the newline,and the star character means "zero or more of the preceding character enter the following into the interactive shellnameregex re compile( 'first name*last name*)'mo nameregex search('first nameal last namesweigart'mo group( 'almo group( 'sweigartpattern matching with regular expressions |
2,660 | possible to match any and all text in non-greedy fashionuse the dotstarand question mark *?like with bracesthe question mark tells python to match in non-greedy way enter the following into the interactive shell to see the difference between the greedy and non-greedy versionsnongreedyregex re compile( ''mo nongreedyregex search(for dinner >'mo group('greedyregex re compile( ''mo greedyregex search(for dinner >'mo group(for dinner >both regexes roughly translate to "match an opening angle bracketfollowed by anythingfollowed by closing angle bracket but the string for dinner >has two possible matches for the closing angle bracket in the non-greedy version of the regexpython matches the shortest possible string'in the greedy versionpython matches the longest possible stringfor dinner >matching newlines with the dot character the dot-star will match everything except newline by passing re dotall as the second argument to re compile()you can make the dot character match all charactersincluding the newline character enter the following into the interactive shellnonewlineregex re compile(*'nonewlineregex search('serve the public trust \nprotect the innocent \nuphold the law 'group('serve the public trust newlineregex re compile(*'re dotallnewlineregex search('serve the public trust \nprotect the innocent \nuphold the law 'group('serve the public trust \nprotect the innocent \nuphold the law the regex nonewlineregexwhich did not have re dotall passed to the re compile(call that created itwill match everything only up to the first newline characterwhereas newlineregexwhich did have re dotall passed to re compile()matches everything this is why the newlineregex search(call matches the full stringincluding its newline characters |
2,661 | this covered lot of notationso here' quick review of what you learned about basic regular expression syntaxthe matches zero or one of the preceding group the matches zero or more of the preceding group the matches one or more of the preceding group the {nmatches exactly of the preceding group the { ,matches or more of the preceding group the {,mmatches to of the preceding group the { ,mmatches at least and at most of the preceding group { , }or *or +performs non-greedy match of the preceding group ^spam means the string must begin with spam spammeans the string must end with spam the matches any characterexcept newline characters \ \wand \ match digitwordor space characterrespectively \ \wand \ match anything except digitwordor space characterrespectively [abcmatches any character between the brackets (such as abor [^abcmatches any character that isn' between the brackets case-insensitive matching normallyregular expressions match text with the exact casing you specify for examplethe following regexes match completely different stringsregex re compile('robocop'regex re compile('robocop'regex re compile('robocop'regex re compile('robocop'but sometimes you care only about matching the letters without worrying whether they're uppercase or lowercase to make your regex caseinsensitiveyou can pass re ignorecase or re as second argument to re compile(enter the following into the interactive shellrobocop re compile( 'robocop're irobocop search('robocop is part manpart machineall cop 'group('robocoprobocop search('robocop protects the innocent 'group('robocoprobocop search('alwhy does your programming book talk about robocop so much?'group('robocoppattern matching with regular expressions |
2,662 | regular expressions can not only find text patterns but can also substitute new text in place of those patterns the sub(method for regex objects is passed two arguments the first argument is string to replace any matches the second is the string for the regular expression the sub(method returns string with the substitutions applied for exampleenter the following into the interactive shellnamesregex re compile( 'agent \ +'namesregex sub('censored''agent alice gave the secret documents to agent bob ''censored gave the secret documents to censored sometimes you may need to use the matched text itself as part of the substitution in the first argument to sub()you can type \ \ \ and so onto mean "enter the text of group and so onin the substitution for examplesay you want to censor the names of the secret agents by showing just the first letters of their names to do thisyou could use the regex agent (\ )\wand pass '\ ****as the first argument to sub(the \ in that string will be replaced by whatever text was matched by group -that isthe (\wgroup of the regular expression agentnamesregex re compile( 'agent (\ )\ *'agentnamesregex sub( '\ ****''agent alice told agent carol that agent eve knew agent bob was double agent ' ***told ***that ***knew ***was double agent managing complex regexes regular expressions are fine if the text pattern you need to match is simple but matching complicated text patterns might require longconvoluted regular expressions you can mitigate this by telling the re compile(function to ignore whitespace and comments inside the regular expression string this "verbose modecan be enabled by passing the variable re verbose as the second argument to re compile(now instead of hard-to-read regular expression like thisphoneregex re compile( '((\ { }|\(\ { }\))?(\ |-|)?\ { }(\ |-|)\ { (\ *(ext| |ext )\ *\ { , })?)'you can spread the regular expression over multiple lines with comments like thisphoneregex re compile( '''(\ { }|\(\ { }\))(\ |-|)\ { (\ |-|\ { area code separator first digits separator last digits |
2,663 | )'''re verboseextension note how the previous example uses the triple-quote syntax ('''to create multiline string so that you can spread the regular expression definition over many linesmaking it much more legible the comment rules inside the regular expression string are the same as regular python codethe symbol and everything after it to the end of the line are ignored alsothe extra spaces inside the multiline string for the regular expression are not considered part of the text pattern to be matched this lets you organize the regular expression so it' easier to read combining re ignorecasere dotalland re verbose what if you want to use re verbose to write comments in your regular expression but also want to use re ignorecase to ignore capitalizationunfortunatelythe re compile(function takes only single value as its second argument you can get around this limitation by combining the re ignorecasere dotalland re verbose variables using the pipe character (|)which in this context is known as the bitwise or operator so if you want regular expression that' case-insensitive and includes newlines to match the dot characteryou would form your re compile(call like thissomeregexvalue re compile('foo're ignorecase re dotallincluding all three options in the second argument will look like thissomeregexvalue re compile('foo're ignorecase re dotall re verbosethis syntax is little old-fashioned and originates from early versions of python the details of the bitwise operators are beyond the scope of this bookbut check out the resources at more information you can also pass other options for the second argumentthey're uncommonbut you can read more about them in the resourcestoo projectphone number and email address extractor say you have the boring task of finding every phone number and email address in long web page or document if you manually scroll through the pageyou might end up searching for long time but if you had program that could search the text in your clipboard for phone numbers and email addressesyou could simply press ctrl- to select all the textpress ctrl - to copy it to the clipboardand then run your program it could replace the text on the clipboard with just the phone numbers and email addresses it finds pattern matching with regular expressions |
2,664 | into writing code but more often than notit' best to take step back and consider the bigger picture recommend first drawing up high-level plan for what your program needs to do don' think about the actual code yet-you can worry about that later right nowstick to broad strokes for exampleyour phone and email address extractor will need to do the following get the text off the clipboard find all phone numbers and email addresses in the text paste them onto the clipboard now you can start thinking about how this might work in code the code will need to do the following use the pyperclip module to copy and paste strings create two regexesone for matching phone numbers and the other for matching email addresses find all matchesnot just the first matchof both regexes neatly format the matched strings into single string to paste display some kind of message if no matches were found in the text this list is like road map for the project as you write the codeyou can focus on each of these steps separately each step is fairly manageable and expressed in terms of things you already know how to do in python step create regex for phone numbers firstyou have to create regular expression to search for phone numbers create new fileenter the followingand save it as phoneandemail py#python phoneandemail py finds phone numbers and email addresses on the clipboard import pyperclipre phoneregex re compile( '''(\ { }|\(\ { }\))(\ |-|)(\ { }(\ |-|(\ { }(\ *(ext| |ext )\ *(\ { , })))'''re verbosearea code separator first digits separator last digits extension todocreate email regex todofind matches in clipboard text todocopy results to the clipboard |
2,665 | replaced as you write the actual code the phone number begins with an optional area codeso the area code group is followed with question mark since the area code can be just three digits (that is\ { }or three digits within parentheses (that is\(\ { }\))you should have pipe joining those parts you can add the regex comment area code to this part of the multiline string to help you remember what (\ { }|\(\ { }\))is supposed to match the phone number separator character can be space (\ )hyphen (-)or period )so these parts should also be joined by pipes the next few parts of the regular expression are straightforwardthree digitsfollowed by another separatorfollowed by four digits the last part is an optional extension made up of any number of spaces followed by extxor ext followed by two to five digits note it' easy to get mixed up with regular expressions that contain groups with parentheses and escaped parentheses \\remember to double-check that you're using the correct one if you get "missing )unterminated subpatternerror message step create regex for email addresses you will also need regular expression that can match email addresses make your program look like the following#python phoneandemail py finds phone numbers and email addresses on the clipboard import pyperclipre phoneregex re compile( '''--snip-create email regex emailregex re compile( '''[ -za- - %+-]username symbol [ -za- - -]domain name ([ -za- ]{ , }dot-something )'''re verbosetodofind matches in clipboard text todocopy results to the clipboard the username part of the email address is one or more characters that can be any of the followinglowercase and uppercase lettersnumbersa dotan underscorea percent signa plus signor hyphen you can put all of these into character class[ -za- - %+-the domain and username are separated by an symbol the domain name has slightly less permissive character class with only lettersnumbersperiodsand hyphens[ -za- - -and last will be pattern matching with regular expressions |
2,666 | really be dot-anything this is between two and four characters the format for email addresses has lot of weird rules this regular expression won' match every possible valid email addressbut it'll match almost any typical email address you'll encounter step find all matches in the clipboard text now that you have specified the regular expressions for phone numbers and email addressesyou can let python' re module do the hard work of finding all the matches on the clipboard the pyperclip paste(function will get string value of the text on the clipboardand the findall(regex method will return list of tuples make your program look like the following#python phoneandemail py finds phone numbers and email addresses on the clipboard import pyperclipre phoneregex re compile( '''--snip-find matches in clipboard text text str(pyperclip paste()matches [for groups in phoneregex findall(text)phonenum '-join([groups[ ]groups[ ]groups[ ]]if groups[ !''phonenum +xgroups[ matches append(phonenumfor groups in emailregex findall(text)matches append(groups[ ]todocopy results to the clipboard there is one tuple for each matchand each tuple contains strings for each group in the regular expression remember that group matches the entire regular expressionso the group at index of the tuple is the one you are interested in as you can see at you'll store the matches in list variable named matches it starts off as an empty listand couple for loops for the email addressesyou append group of each match for the matched phone numbersyou don' want to just append group while the program detects phone numbers in several formatsyou want the phone number appended to be in singlestandard format the phonenum variable contains string built from groups and of the matched text (these groups are the area codefirst three digitslast four digitsand extension |
2,667 | now that you have the email addresses and phone numbers as list of strings in matchesyou want to put them on the clipboard the pyperclip copy(function takes only single string valuenot list of stringsso you call the join(method on matches to make it easier to see that the program is workinglet' print any matches you find to the terminal if no phone numbers or email addresses were foundthe program should tell the user this make your program look like the following#python phoneandemail py finds phone numbers and email addresses on the clipboard --snip-for groups in emailregex findall(text)matches append(groups[ ]copy results to the clipboard if len(matches pyperclip copy('\njoin(matches)print('copied to clipboard:'print('\njoin(matches)elseprint('no phone numbers or email addresses found 'running the program for an exampleopen your web browser to the no starch press contact page at pageand press ctrl- to copy it to the clipboard when you run this programthe output will look something like thiscopied to clipboardinfo@nostarch com media@nostarch com academic@nostarch com info@nostarch com ideas for similar programs identifying patterns of text (and possibly substituting them with the sub(methodhas many different potential applications for exampleyou couldfind website urls that begin with clean up dates in different date formats (such as and by replacing them with dates in singlestandard format pattern matching with regular expressions |
2,668 | remove sensitive information such as social security or credit card numbers find common typos such as multiple spaces between wordsaccidentally accidentally repeated wordsor multiple exclamation marks at the end of sentences those are annoying!summary while computer can search for text quicklyit must be told precisely what to look for regular expressions allow you to specify the pattern of characters you are looking forrather than the exact text itself in factsome word processing and spreadsheet applications provide find-and-replace features that allow you to search using regular expressions the re module that comes with python lets you compile regex objects these objects have several methodssearch(to find single matchfindall(to find all matching instancesand sub(to do find-and-replace substitution of text you can find out more in the official python documentation at docs python org/ /library/re html another useful resource is the tutorial website practice questions what is the function that creates regex objectswhy are raw strings often used when creating regex objectswhat does the search(method returnhow do you get the actual strings that match the pattern from match object in the regex created from '(\ \ \ )-(\ \ \ -\ \ \ \ )'what does group covergroup group parentheses and periods have specific meanings in regular expression syntax how would you specify that you want regex to match actual parentheses and period characters the findall(method returns list of strings or list of tuples of strings what makes it return one or the other what does the character signify in regular expressions what two things does the character signify in regular expressions what is the difference between the and characters in regular expressions what is the difference between { and { , in regular expressions what do the \ \wand \ shorthand character classes signify in regular expressions |
2,669 | regular expressions what is the difference between and *? what is the character class syntax to match all numbers and lowercase letters how do you make regular expression case-insensitive what does the character normally matchwhat does it match if re dotall is passed as the second argument to re compile() if numregex re compile( '\ +')what will numregex sub(' '' drummers pipersfive rings hens'return what does passing re verbose as the second argument to re compile(allow you to do how would you write regex that matches number with commas for every three digitsit must match the following' ' , ' , , but not the following' , , (which has only two digits between the commas' (which lacks commas how would you write regex that matches the full name of someone whose last name is watanabeyou can assume that the first name that comes before it will always be one word that begins with capital letter the regex must match the following'haruto watanabe'alice watanabe'robocop watanabebut not the following'haruto watanabe(where the first name is not capitalized'mr watanabe(where the preceding word has nonletter character'watanabe(which has no first name'haruto watanabe(where watanabe is not capitalized how would you write regex that matches sentence where the first word is either alicebobor carolthe second word is either eatspetsor throwsthe third word is applescatsor baseballsand the sentence ends with periodthis regex should be case-insensitive it must match the following'alice eats apples 'bob pets cats 'carol throws baseballs 'alice throws apples 'bob eats cats pattern matching with regular expressions |
2,670 | 'robocop eats apples 'alice throws footballs 'carol eats cats practice projects for practicewrite programs to do the following tasks date detection write regular expression that can detect dates in the dd/mm/yyyy format assume that the days range from to the months range from to and the years range from to note that if the day or month is single digitit'll have leading zero the regular expression doesn' have to detect correct days for each month or for leap yearsit will accept nonexistent dates like or then store these strings into variables named monthdayand yearand write additional code that can detect if it is valid date apriljuneseptemberand november have daysfebruary has daysand the rest of the months have days february has days in leap years leap years are every year evenly divisible by except for years evenly divisible by unless the year is also evenly divisible by note how this calculation makes it impossible to make reasonably sized regular expression that can detect valid date strong password detection write function that uses regular expressions to make sure the password string it is passed is strong strong password is defined as one that is at least eight characters longcontains both uppercase and lowercase charactersand has at least one digit you may need to test the string against multiple regex patterns to validate its strength regex version of the strip(method write function that takes string and does the same thing as the strip(string method if no other arguments are passed other than the string to stripthen whitespace characters will be removed from the beginning and end of the string otherwisethe characters specified in the second argument to the function will be removed from the string |
2,671 | inpu va lidat ion input validation code checks that values entered by the usersuch as text from the input(functionare formatted correctly for exampleif you want users to enter their agesyour code shouldn' accept nonsensical answers such as negative numbers (which are outside the range of acceptable integersor words (which are the wrong data typeinput validation can also prevent bugs or security vulnerabilities if you implement withdrawfromaccount(function that takes an argument for the amount to subtract from an accountyou need to ensure the amount is positive number if the withdrawfromaccount(function subtracts negative number from the accountthe "withdrawalwill end up adding money |
2,672 | input until they enter valid textas in the following examplewhile trueprint('enter your age:'age input(tryage int(ageexceptprint('please use numeric digits 'continue if age print('please enter positive number 'continue break print( 'your age is {age'when you run this programthe output could look like thisenter your agefive please use numeric digits enter your age- please enter positive number enter your age your age is when you run this codeyou'll be prompted for your age until you enter valid one this ensures that by the time the execution leaves the while loopthe age variable will contain valid value that won' crash the program later on howeverwriting input validation code for every input(call in your program quickly becomes tedious alsoyou may miss certain cases and allow invalid input to pass through your checks in this you'll learn how to use the third-party pyinputplus module for input validation the pyinputplus module pyinputplus contains functions similar to input(for several kinds of datanumbersdatesemail addressesand more if the user ever enters invalid inputsuch as badly formatted date or number that is outside of an intended rangepyinputplus will reprompt them for input just like our code in the previous section did pyinputplus also has other useful features like limit for the number of times it reprompts users and timeout if users are required to respond within time limit |
2,673 | install it separately using pip to install pyinputplusrun pip install --user pyinputplus from the command line appendix has complete instructions for installing third-party modules to check if pyinputplus installed correctlyimport it in the interactive shellimport pyinputplus if no errors appear when you import the moduleit has been successfully installed pyinputplus has several functions for different kinds of inputis like the built-in input(function but has the general pyinputplus features you can also pass custom validation function to it inputnum(ensures the user enters number and returns an int or floatdepending on if the number has decimal point in it inputchoice(ensures the user enters one of the provided choices inputmenu(is similar to inputchoice()but provides menu with numbered or lettered options inputdatetime(ensures the user enters date and time inputyesno(ensures the user enters "yesor "noresponse inputbool(is similar to inputyesno()but takes "trueor "falseresponse and returns boolean value inputemail(ensures the user enters valid email address inputfilepath(ensures the user enters valid file path and filenameand can optionally check that file with that name exists inputpassword(is like the built-in input()but displays characters as the user types so that passwordsor other sensitive informationaren' displayed on the screen inputstr(these functions will automatically reprompt the user for as long as they enter invalid inputimport pyinputplus as pyip response pyip inputnum(five 'fiveis not number response the as pyip code in the import statement saves us from typing pyinputplus each time we want to call pyinputplus function instead we can use the shorter pyip name if you take look at the exampleyou see that unlike input()these functions return an int or float value and instead of the strings ' and ' input validation |
2,674 | pass string to pyinputplus function' prompt keyword argument to display promptresponse input('enter number'enter number response ' import pyinputplus as pyip response pyip inputint(prompt='enter number'enter numbercat 'catis not an integer enter number response use python' help(function to find out more about each of these functions for examplehelp(pyip inputchoicedisplays help information for the inputchoice(function complete documentation can be found at unlike python' built-in input()pyinputplus functions have several additional features for input validationas shown in the next section the minmaxgreaterthanand lessthan keyword arguments the inputnum()inputint()and inputfloat(functionswhich accept int and float numbersalso have minmaxgreaterthanand lessthan keyword arguments for specifying range of valid values for exampleenter the following into the interactive shellimport pyinputplus as pyip response pyip inputnum('enter num'min= enter num: input must be at minimum enter num: response response pyip inputnum('enter num'greaterthan= enter num input must be greater than enter num response response pyip inputnum('>'min= lessthan= enter num input must be less than enter num input must be at minimum enter num response |
2,675 | the input can be equal to themalsothe input must be greater than the greaterthan and less than the lessthan arguments (that isthe input cannot be equal to themthe blank keyword argument by defaultblank input isn' allowed unless the blank keyword argument is set to trueimport pyinputplus as pyip response pyip inputnum('enter num'enter num:(blank input entered hereblank values are not allowed enter num response response pyip inputnum(blank=true(blank input entered hereresponse 'use blank=true if you' like to make input optional so that the user doesn' need to enter anything the limittimeoutand default keyword arguments by defaultthe pyinputplus functions will continue to ask the user for valid input forever (or for as long as the program runsif you' like function to stop asking the user for input after certain number of tries or certain amount of timeyou can use the limit and timeout keyword arguments pass an integer for the limit keyword argument to determine how many attempts pyinputplus function will make to receive valid input before giving upand pass an integer for the timeout keyword argument to determine how many seconds the user has to enter valid input before the pyinputplus function gives up if the user fails to enter valid inputthese keyword arguments will cause the function to raise retrylimitexception or timeoutexceptionrespectively for exampleenter the following into the interactive shellimport pyinputplus as pyip response pyip inputnum(limit= blah 'blahis not number enter numnumber 'numberis not number traceback (most recent call last)--snip-pyinputplus retrylimitexception response pyip inputnum(timeout= (entered after seconds of waitinginput validation |
2,676 | --snip-pyinputplus timeoutexception when you use these keyword arguments and also pass default keyword argumentthe function returns the default value instead of raising an exception enter the following into the interactive shellresponse pyip inputnum(limit= default=' / 'hello 'hellois not number world 'worldis not number response ' /ainstead of raising retrylimitexceptionthe inputnum(function simply returns the string ' /athe allowregexes and blockregexes keyword arguments you can also use regular expressions to specify whether an input is allowed or not the allowregexes and blockregexes keyword arguments take list of regular expression strings to determine what the pyinputplus function will accept or reject as valid input for exampleenter the following code into the interactive shell so that inputnum(will accept roman numerals in addition to the usual numbersimport pyinputplus as pyip response pyip inputnum(allowregexes=[ '( | | | | | | )+' 'zero']xlii response 'xliiresponse pyip inputnum(allowregexes=[ '( | | | | | | )+' 'zero']xlii response 'xliiof coursethis regex affects only what letters the inputnum(function will accept from the userthe function will still accept roman numerals with invalid ordering such as 'xvxor 'millibecause the '( | | | | | | )+regular expression accepts those strings you can also specify list of regular expression strings that pyinputplus function won' accept by using the blockregexes keyword argument enter the following into the interactive shell so that inputnum(won' accept even numbersimport pyinputplus as pyip response pyip inputnum(blockregexes=[ '[ ]$'] this response is invalid |
2,677 | this response is invalid response if you specify both an allowregexes and blockregexes argumentthe allow list overrides the block list for exampleenter the following into the interactive shellwhich allows 'caterpillarand 'categorybut blocks anything else that has the word 'catin itimport pyinputplus as pyip response pyip inputstr(allowregexes=[ 'caterpillar''category']blockregexes=[ 'cat']cat this response is invalid catastrophe this response is invalid category response 'categorythe pyinputplus module' functions can save you from writing tedious input validation code yourself but there' more to the pyinputplus module than what has been detailed here you can examine its full documentation online at passing custom validation function to inputcustom(you can write function to perform your own custom validation logic by passing the function to inputcustom(for examplesay you want the user to enter series of digits that adds up to there is no pyinputplus inputaddsuptoten(functionbut you can create your own function thataccepts single string argument of what the user entered raises an exception if the string fails validation returns none (or has no return statementif inputcustom(should return the string unchanged returns nonnone value if inputcustom(should return different string from the one the user entered is passed as the first argument to inputcustom(for examplewe can create our own addsuptoten(functionand then pass it to inputcustom(note that the function call looks like inputcustom(addsuptotenand not inputcustom(addsuptoten()because we are passing the addsuptoten(function itself to inputcustom()not calling addsuptoten(and passing its return value import pyinputplus as pyip def addsuptoten(numbers)input validation |
2,678 | numberslist list(numbersfor idigit in enumerate(numberslist)numberslist[iint(digitif sum(numberslist! raise exception('the digits must add up to not % (sum(numberslist))return int(numbersreturn an int form of numbers response pyip inputcustom(addsuptotenno parentheses after addsuptoten here the digits must add up to not the digits must add up to not response inputstr(returned an intnot string response pyip inputcustom(addsuptotenhello invalid literal for int(with base ' response the inputcustom(function also supports the general pyinputplus featuressuch as the blanklimittimeoutdefaultallowregexesand blockregexes keyword arguments writing your own custom validation function is useful when it' otherwise difficult or impossible to write regular expression for valid inputas in the "adds up to example projecthow to keep an idiot busy for hours let' use pyinputplus to create simple program that does the following ask the user if they' like to know how to keep an idiot busy for hours if the user answers noquit if the user answers yesgo to step of coursewe don' know if the user will enter something besides "yesor "no,so we need to perform input validation it would also be convenient for the user to be able to enter "yor "ninstead of the full words pyinputplus' inputyesno(function will handle this for us andno matter what case the user entersreturn lowercase 'yesor 'nostring value when you run this programit should look like the followingwant to know how to keep an idiot busy for hourssure 'sureis not valid yes/no response want to know how to keep an idiot busy for hoursyes want to know how to keep an idiot busy for hoursy |
2,679 | yes want to know how to keep an idiot busy for hoursyes want to know how to keep an idiot busy for hoursyes!!!!!'yes!!!!!!is not valid yes/no response want to know how to keep an idiot busy for hourstell me how to keep an idiot busy for hours 'tell me how to keep an idiot busy for hours is not valid yes/no response want to know how to keep an idiot busy for hoursno thank you have nice day open new file editor tab and save it as idiot py then enter the following codeimport pyinputplus as pyip this imports the pyinputplus module since pyinputplus is bit much to typewe'll use the name pyip for short while trueprompt 'want to know how to keep an idiot busy for hours?\nresponse pyip inputyesno(promptnextwhile truecreates an infinite loop that continues to run until it encounters break statement in this loopwe call pyip inputyesno(to ensure that this function call won' return until the user enters valid answer if response ='no'break the pyip inputyesno(call is guaranteed to only return either the string yes or the string no if it returned nothen our program breaks out of the infinite loop and continues to the last linewhich thanks the userprint('thank you have nice day 'otherwisethe loop iterates once again you can also make use of the inputyesno(function in non-english languages by passing yesval and noval keyword arguments for examplethe spanish version of this program would have these two linesprompt '?quieres saber como mantener ocupado un idiota durante horas?\nresponse pyip inputyesno(promptyesval='si'noval='no'if response ='si'now the user can enter either si or (in loweror uppercaseinstead of yes or for an affirmative answer input validation |
2,680 | pyinputplus' features can be useful for creating timed multiplication quiz by setting the allowregexesblockregexestimeoutand limit keyword argument to pyip inputstr()you can leave most of the implementation to pyinputplus the less code you need to writethe faster you can write your programs let' create program that poses multiplication problems to the userwhere the valid input is the problem' correct answer open new file editor tab and save the file as multiplicationquiz py firstwe'll import pyinputplusrandomand time we'll keep track of how many questions the program asks and how many correct answers the user gives with the variables numberofquestions and correctanswers for loop will repeatedly pose random multiplication problem timesimport pyinputplus as pyip import randomtime numberofquestions correctanswers for questionnumber in range(numberofquestions)inside the for loopthe program will pick two single-digit numbers to multiply we'll use these numbers to create #qn prompt for the userwhere is the question number ( to and are the two numbers to multiply pick two random numbersnum random randint( num random randint( prompt '#% % % (questionnumbernum num the pyip inputstr(function will handle most of the features of this quiz program the argument we pass for allowregexes is list with the regex string '^% $'where % is replaced with the correct answer the and characters ensure that the answer begins and ends with the correct numberthough pyinputplus trims any whitespace from the start and end of the user' response first just in case they inadvertently pressed the spacebar before or after their answer the argument we pass for blocklistregexes is list with (*''incorrect!'the first string in the tuple is regex that matches every possible string thereforeif the user response doesn' match the correct answerthe program will reject any other answer they provide in that casethe 'incorrect!string is displayed and the user is prompted to answer again additionallypassing for timeout and for limit will ensure that the user only has seconds and tries to provide correct answertryright answers are handled by allowregexes wrong answers are handled by blockregexeswith custom message pyip inputstr(promptallowregexes=['^% $(num num )] |
2,681 | timeout= limit= if the user answers after the -second timeout has expiredeven if they answer correctlypyip inputstr(raises timeoutexception exception if the user answers incorrectly more than timesit raises retrylimitexception exception both of these exception types are in the pyinputplus moduleso pyip needs to prepend themexcept pyip timeoutexceptionprint('out of time!'except pyip retrylimitexceptionprint('out of tries!'remember thatjust like how else blocks can follow an if or elif blockthey can optionally follow the last except block the code inside the following else block will run if no exception was raised in the try block in our casethat means the code runs if the user entered the correct answerelsethis block runs if no exceptions were raised in the try block print('correct!'correctanswers + no matter which of the three messages"out of time!""out of tries!"or "correct!"displayslet' place -second pause at the end of the for loop to give the user time to read it after the program has asked questions and the for loop continueslet' show the user how many correct answers they madetime sleep( brief pause to let user see the result print('score% % (correctanswersnumberofquestions)pyinputplus is flexible enough that you can use it in wide variety of programs that take keyboard input from the useras demonstrated by the programs in this summary it' easy to forget to write input validation codebut without ityour programs will almost certainly have bugs the values you expect users to enter and the values they actually enter can be completely differentand your programs need to be robust enough to handle these exceptional cases you can use regular expressions to create your own input validation codebut for common casesit' easier to use an existing modulesuch as pyinputplus you can import the module with import pyinputplus as pyip so that you can enter shorter name when calling the module' functions pyinputplus has functions for entering variety of inputincluding stringsnumbersdatesyes/notrue/falseemailsand files while input(input validation |
2,682 | pre-selected optionswhile inputmenu(also adds numbers or letters for quick selection all of these functions have the following standard featuresstripping whitespace from the sidessetting timeout and retry limits with the timeout and limit keyword argumentsand passing lists of regular expression strings to allowregexes or blockregexes to include or exclude particular responses you'll no longer need to write your own tedious while loops that check for valid input and reprompt the user if none of the pyinputplus module'sfunctions fit your needsbut you' still like the other features that pyinputplus providesyou can call inputcustom(and pass your own custom validation function for pyinputplus to use the documentation at complete listing of pyinputplus' functions and additional features there' far more in the pyinputplus online documentation than what was described in this there' no use in reinventing the wheeland learning to use this module will save you from having to write and debug code for yourself now that you have expertise manipulating and validating textit' time to learn how to read from and write to files on your computer' hard drive practice questions does pyinputplus come with the python standard librarywhy is pyinputplus commonly imported with import pyinputplus as pyipwhat is the difference between inputint(and inputfloat()how can you ensure that the user enters whole number between and using pyinputpluswhat is passed to the allowregexes and blockregexes keyword argumentswhat does inputstr(limit= do if blank input is entered three timeswhat does inputstr(limit= default='hello'do if blank input is entered three timespractice projects for practicewrite programs to do the following tasks sandwich maker write program that asks users for their sandwich preferences the program should use pyinputplus to ensure that they enter valid inputsuch as using inputmenu(for bread typewheatwhiteor sourdough using inputmenu(for protein typechickenturkeyhamor tofu |
2,683 | using inputyesno(to ask if they want cheese if sousing inputmenu(to ask for cheese typecheddarswissor mozzarella using inputyesno(to ask if they want mayomustardlettuceor tomato using inputint(to ask how many sandwiches they want make sure this number is or more come up with prices for each of these optionsand have your program display total cost after the user enters their selection write your own multiplication quiz to see how much pyinputplus is doing for youtry re-creating the multiplication quiz project on your own without importing it this program will prompt the user with multiplication questionsranging from to you'll need to implement the following featuresif the user enters the correct answerthe program displays "correct!for second and moves on to the next question the user gets three tries to enter the correct answer before the program moves on to the next question eight seconds after first displaying the questionthe question is marked as incorrect even if the user enters the correct answer after the -second limit compare your code to the code using pyinputplus in "projectmultiplication quizon page input validation |
2,684 | re ading and writing files variables are fine way to store data while your program is runningbut if you want your data to persist even after your program has finishedyou need to save it to file you can think of file' contents as single string valuepotentially gigabytes in size in this you will learn how to use python to createreadand save files on the hard drive files and file paths file has two key propertiesa filename (usually written as one wordand path the path specifies the location of file on the computer for examplethere is file on my windows laptop with the filename project docx in the path :\users\al\documents the part of the filename after the last period is called the file' extension and tells you file' type the filename project docx |
2,685 | called directoriesfolders can contain files and other folders for exampleproject docx is in the documents folderwhich is inside the al folderwhich is inside the users folder figure - shows this folder organization :users ai documents project docx figure - file in hierarchy of folders the :part of the path is the root folderwhich contains all other folders on windowsthe root folder is named :and is also called the cdrive on macos and linuxthe root folder is in this booki'll use the windows-style root folderc:if you are entering the interactive shell examples on macos or linuxenter instead additional volumessuch as dvd drive or usb flash drivewill appear differently on different operating systems on windowsthey appear as newlettered root drivessuch as :or :on macosthey appear as new folders under the /volumes folder on linuxthey appear as new folders under the /mnt ("mount"folder also note that while folder names and filenames are not case-sensitive on windows and macosthey are case-sensitive on linux note since your system probably has different files and folders on it than mineyou won' be able to follow every example in this exactly stilltry to follow along using folders that exist on your computer backslash on windows and forward slash on macos and linux on windowspaths are written using backslashes (\as the separator between folder names the macos and linux operating systemshoweveruse the forward slash (/as their path separator if you want your programs to work on all operating systemsyou will have to write your python scripts to handle both cases fortunatelythis is simple to do with the path(function in the pathlib module if you pass it the string values of individual file and folder names in your pathpath(will return string with file path using the correct path separators enter the following into the interactive shellfrom pathlib import path path('spam''bacon''eggs'windowspath('spam/bacon/eggs' |
2,686 | 'spam\\bacon\\eggsnote that the convention for importing pathlib is to run from pathlib import pathsince otherwise we' have to enter pathlib path everywhere path shows up in our code not only is this extra typing redundantbut it' also redundant ' running this interactive shell examples on windowsso path('spam''bacon''eggs'returned windowspath object for the joined pathrepresented as windowspath('spam/bacon/eggs'even though windows uses backslashesthe windowspath representation in the interactive shell displays them using forward slashessince open source software developers have historically favored the linux operating system if you want to get simple text string of this pathyou can pass it to the str(functionwhich in our example returns 'spam\\bacon\\eggs(notice that the backslashes are doubled because each backslash needs to be escaped by another backslash character if had called this function onsaylinuxpath(would have returned posixpath object thatwhen passed to str()would have returned 'spam/bacon/eggs(posix is set of standards for unix-like operating systems such as linux these path objects (reallywindowspath or posixpath objectsdepending on your operating systemwill be passed to several of the file-related functions introduced in this for examplethe following code joins names from list of filenames to the end of folder' namefrom pathlib import path myfiles ['accounts txt''details csv''invite docx'for filename in myfilesprint(path( ' :\users\al'filename) :\users\al\accounts txt :\users\al\details csv :\users\al\invite docx on windowsthe backslash separates directoriesso you can' use it in filenames howeveryou can use backslashes in filenames on macos and linux so while path( 'spam\eggs'refers to two separate folders (or file eggs in folder spamon windowsthe same command would refer to single folder (or filenamed spam\eggs on macos and linux for this reasonit' usually good idea to always use forward slashes in your python code (and 'll be doing so for the rest of this the pathlib module will ensure that it always works on all operating systems note that pathlib was introduced in python to replace older os path functions the python standard library modules support it as of python but if you are working with legacy python versionsi recommend using pathlib which gives you pathlib' features on python appendix has instructions for installing pathlib using pip whenever 've replaced an older os path function with pathlibi've made short note you can look up the older functions at reading and writing files |
2,687 | we normally use the operator to add two integer or floating-point numberssuch as in the expression which evaluates to the integer value but we can also use the operator to concatenate two string valueslike the expression 'hello'world'which evaluates to the string value 'helloworldsimilarlythe operator that we normally use for division can also combine path objects and strings this is helpful for modifying path object after you've already created it with the path(function for exampleenter the following into the interactive shellfrom pathlib import path path('spam''bacon'eggswindowspath('spam/bacon/eggs'path('spam'path('bacon/eggs'windowspath('spam/bacon/eggs'path('spam'path('bacon''eggs'windowspath('spam/bacon/eggs'using the operator with path objects makes joining paths just as easy as string concatenation it' also safer than using string concatenation or the join(methodlike we do in this examplehomefolder ' :\users\alsubfolder 'spamhomefolder '\\subfolder ' :\\users\\al\\spam'\\join([homefoldersubfolder]' :\\users\\al\\spama script that uses this code isn' safebecause its backslashes would only work on windows you could add an if statement that checks sys platform (which contains string describing the computer' operating systemto decide what kind of slash to usebut applying this custom code everywhere it' needed can be inconsistent and bug-prone the pathlib module solves these problems by reusing the math division operator to join paths correctlyno matter what operating system your code is running on the following example uses this strategy to join the same paths as in the previous examplehomefolder path(' :/users/al'subfolder path('spam'homefolder subfolder windowspath(' :/users/al/spam'str(homefolder subfolder' :\\users\\al\\spamthe only thing you need to keep in mind when using the operator for joining paths is that one of the first two values must be path object |
2,688 | interactive shell'spam'bacon'eggstraceback (most recent call last)file ""line in typeerrorunsupported operand type(sfor /'strand 'strpython evaluates the operator from left to right and evaluates to path objectso either the first or second leftmost value must be path object for the entire expression to evaluate to path object here' how the operator and path object evaluate to the final path object path('spam)/'bacon/'eggs'/'hamwindowspath('spam/bacon')/'eggs'/'hamwindowspath('spam/bacon/eggs'/'hamwindowspath('spam/bacon/eggs/ham'if you see the typeerrorunsupported operand type(sfor /'strand 'strerror message shown previouslyyou need to put path object on the left side of the expression the operator replaces the older os path join(functionwhich you can learn more about from path join the current working directory every program that runs on your computer has current working directoryor cwd any filenames or paths that do not begin with the root folder are assumed to be under the current working directory note while folder is the more modern name for directorynote that current working directory (or just working directoryis the standard termnot "current working folder you can get the current working directory as string value with the path cwd(function and change it using os chdir(enter the following into the interactive shellfrom pathlib import path import os path cwd(windowspath(' :/users/al/appdata/local/programs/python/python ')os chdir(' :\\windows\\system 'path cwd(windowspath(' :/windows/system 'reading and writing files |
2,689 | \programs\python\python so the filename project docx refers to :\users\al \appdata\local\programs\python\python \project docx when we change the current working directory to :\windows\system the filename project docx is interpreted as :\windows\system \project docx python will display an error if you try to change to directory that does not exist os chdir(' :/thisfolderdoesnotexist'traceback (most recent call last)file ""line in filenotfounderror[winerror the system cannot find the file specified' :/thisfolderdoesnotexistthere is no pathlib function for changing the working directorybecause changing the current working directory while program is running can often lead to subtle bugs the os getcwd(function is the older way of getting the current working directory as string the home directory all users have folder for their own files on the computer called the home directory or home folder you can get path object of the home folder by calling path home()path home(windowspath(' :/users/al'the home directories are located in set place depending on your operating systemon windowshome directories are under :\users on machome directories are under /users on linuxhome directories are often under /home your scripts will almost certainly have permissions to read and write the files under your home directoryso it' an ideal place to put the files that your python programs will work with absolute vs relative paths there are two ways to specify file pathan absolute pathwhich always begins with the root folder relative pathwhich is relative to the program' current working directory there are also the dot and dot-dot folders these are not real folders but special names that can be used in path single period |
2,690 | ("dot-dot"means "the parent folder figure - is an example of some folders and files when the current working directory is set to :\baconthe relative paths for the other folders and files are set as they are in the figure :current working directory bacon fizz spam txt spam txt eggs spam txt spam txt relative paths absolute paths : :\bacon \fizz :\bacon\fizz \fizz\spam txt :\bacon\fizz\spam txt \spam txt :\bacon\spam txt \eggs :\eggs \eggs\spam txt :\eggs\spam txt \spam txt :\spam txt figure - the relative paths for folders and files in the working directory :\bacon the at the start of relative path is optional for example\spam txt and spam txt refer to the same file creating new folders using the os makedirs(function your programs can create new folders (directorieswith the os makedirs(function enter the following into the interactive shellimport os os makedirs(' :\\delicious\\walnut\\waffles'this will create not just the :\delicious folder but also walnut folder inside :\delicious and waffles folder inside :\delicious\walnut that isos makedirs(will create any necessary intermediate folders in order to ensure that the full path exists figure - shows this hierarchy of folders :delicious walnut waffles figure - the result of os makedirs(' :\\delicious\\walnut\\waffles'reading and writing files |
2,691 | examplethis code will create spam folder under the home folder on my computerfrom pathlib import path path( ' :\users\al\spam'mkdir(note that mkdir(can only make one directory at timeit won' make several subdirectories at once like os makedirs(handling absolute and relative paths the pathlib module provides methods for checking whether given path is an absolute path and returning the absolute path of relative path calling the is_absolute(method on path object will return true if it represents an absolute path or false if it represents relative path for exampleenter the following into the interactive shellusing your own files and folders instead of the exact ones listed herepath cwd(windowspath(' :/users/al/appdata/local/programs/python/python 'path cwd(is_absolute(true path('spam/bacon/eggs'is_absolute(false to get an absolute path from relative pathyou can put path cwd(in front of the relative path object after allwhen we say "relative path,we almost always mean path that is relative to the current working directory enter the following into the interactive shellpath('my/relative/path'windowspath('my/relative/path'path cwd(path('my/relative/path'windowspath(' :/users/al/appdata/local/programs/python/python /my/relativepath'if your relative path is relative to another path besides the current working directoryjust replace path cwd(with that other path instead the following example gets an absolute path using the home directory instead of the current working directorypath('my/relative/path'windowspath('my/relative/path'path home(path('my/relative/path'windowspath(' :/users/al/my/relative/path' |
2,692 | and relative pathscalling os path abspath(pathwill return string of the absolute path of the argument this is an easy way to convert relative path into an absolute one calling os path isabs(pathwill return true if the argument is an absolute path and false if it is relative path calling os path relpath(pathstartwill return string of relative path from the start path to path if start is not providedthe current working directory is used as the start path try these functions in the interactive shellos path abspath('' :\\users\\al\\appdata\\local\\programs\\python\\python os path abspath(\\scripts'' :\\users\\al\\appdata\\local\\programs\\python\\python \\scriptsos path isabs('false os path isabs(os path abspath(')true since :\users\al\appdata\local\programs\python\python was the working directory when os path abspath(was calledthe "single-dotfolder represents the absolute path ' :\\users\\al\\appdata\\local\\programs\\python\\python enter the following calls to os path relpath(into the interactive shellos path relpath(' :\\windows'' :\\''windowsos path relpath(' :\\windows'' :\\spam\\eggs'\\\windowswhen the relative path is within the same parent folder as the pathbut is within subfolders of different pathsuch as ' :\\windowsand ' :\\spam \\eggs'you can use the "dot-dotnotation to return to the parent folder getting the parts of file path given path objectyou can extract the file path' different parts as strings using several path object attributes these can be useful for constructing new file paths based on existing ones the attributes are diagrammed in figure - reading and writing files |
2,693 | parent name :\users\al\spam txt drive stem suffix /home/al/spam txt anchor parent name figure - the parts of windows (topand macos/linux (bottomfile path the parts of file path include the followingthe anchorwhich is the root folder of the filesystem on windowsthe drivewhich is the single letter that often denotes physical hard drive or other storage device the parentwhich is the folder that contains the file the name of the filemade up of the stem (or base nameand the suffix (or extensionnote that windows path objects have drive attributebut macos and linux path objects don' the drive attribute doesn' include the first backslash to extract each attribute from the file pathenter the following into the interactive shellp path(' :/users/al/spam txt' anchor ' :\\ parent this is path objectnot string windowspath(' :/users/al' name 'spam txtp stem 'spamp suffix txtp drive ' :these attributes evaluate to simple string valuesexcept for parentwhich evaluates to another path object |
2,694 | path cwd(windowspath(' :/users/al/appdata/local/programs/python/python 'path cwd(parents[ windowspath(' :/users/al/appdata/local/programs/python'path cwd(parents[ windowspath(' :/users/al/appdata/local/programs'path cwd(parents[ windowspath(' :/users/al/appdata/local'path cwd(parents[ windowspath(' :/users/al/appdata'path cwd(parents[ windowspath(' :/users/al'path cwd(parents[ windowspath(' :/users'path cwd(parents[ windowspath(' :/'the older os path module also has similar functions for getting the different parts of path written in string value calling os path dirname(pathwill return string of everything that comes before the last slash in the path argument calling os path basename(pathwill return string of everything that comes after the last slash in the path argument the directory (or dirname and base name of path are outlined in figure - :\windows\system \calc exe dir name base name figure - the base name follows the last slash in path and is the same as the filename the dir name is everything before the last slash for exampleenter the following into the interactive shellcalcfilepath ' :\\windows\\system \\calc exeos path basename(calcfilepath'calc exeos path dirname(calcfilepath' :\\windows\\system if you need path' dir name and base name togetheryou can just call os path split(to get tuple value with these two stringslike socalcfilepath ' :\\windows\\system \\calc exeos path split(calcfilepath(' :\\windows\\system ''calc exe'reading and writing files |
2,695 | and os path basename(and placing their return values in tuple(os path dirname(calcfilepath)os path basename(calcfilepath)(' :\\windows\\system ''calc exe'but os path split(is nice shortcut if you need both values alsonote that os path split(does not take file path and return list of strings of each folder for thatuse the split(string method and split on the string in os sep (note that sep is in osnot os path the os sep variable is set to the correct folder-separating slash for the computer running the program'\\on windows and '/on macos and linuxand splitting on it will return list of the individual folders for exampleenter the following into the interactive shellcalcfilepath split(os sep[' :''windows''system ''calc exe'this returns all the parts of the path as strings on macos and linux systemsthe returned list of folders will begin with blank stringlike this'/usr/binsplit(os sep['''usr''bin'the split(string method will work to return list of each part of the path finding file sizes and folder contents once you have ways of handling file pathsyou can then start gathering information about specific files and folders the os path module provides functions for finding the size of file in bytes and the files and folders inside given folder calling os path getsize(pathwill return the size in bytes of the file in the path argument calling os listdir(pathwill return list of filename strings for each file in the path argument (note that this function is in the os modulenot os path here' what get when try these functions in the interactive shellos path getsize(' :\\windows\\system \\calc exe' os listdir(' :\\windows\\system '[' '' cpx'' cpx'' ax''aaclient dll'--snip-'xwtpdui dll''xwtpw dll''zh-cn''zh-hk''zh-tw''zipfldr dll' |
2,696 | in sizeand have lot of files in :\windows\system if want to find the total size of all the files in this directoryi can use os path getsize(and os listdir(together totalsize for filename in os listdir(' :\\windows\\system ')totalsize totalsize os path getsize(os path join(' :\\windows\\system 'filename)print(totalsize as loop over each filename in the :\windows\system folderthe totalsize variable is incremented by the size of each file notice how when call os path getsize() use os path join(to join the folder name with the current filename the integer that os path getsize(returns is added to the value of totalsize after looping through all the filesi print totalsize to see the total size of the :\windows\system folder modifying list of files using glob patterns if you want to work on specific filesthe glob(method is simpler to use than listdir(path objects have glob(method for listing the contents of folder according to glob pattern glob patterns are like simplified form of regular expressions often used in command line commands the glob(method returns generator object (which are beyond the scope of this bookthat you'll need to pass to list(to easily view in the interactive shellp path(' :/users/al/desktop' glob('*'list( glob('*')make list from the generator [windowspath(' :/users/al/desktop/ png')windowspath(' :/users/aldesktop/ -ap pdf')windowspath(' :/users/al/desktop/cat jpg')--snip-windowspath(' :/users/al/desktop/zzz txt')the asterisk (*stands for "multiple of any characters,so glob('*'returns generator of all files in the path stored in like with regexesyou can create complex expressionslist( glob('txt'lists all text files [windowspath(' :/users/al/desktop/foo txt')--snip-windowspath(' :/users/al/desktop/zzz txt')the glob pattern 'txtwill return files that start with any combination of characters as long as it ends with the string txt'which is the text file extension reading and writing files |
2,697 | single characterlist( glob('projectdocx'[windowspath(' :/users/al/desktop/project docx')windowspath(' :/users/aldesktop/project docx')--snip-windowspath(' :/users/al/desktop/project docx')the glob expression 'projectdocxwill return 'project docxor 'project docx'but it will not return 'project docx'because only matches to one character--so it will not match to the two-character string ' finallyyou can also combine the asterisk and question mark to create even more complex glob expressionslike thislist( glob('? ?'[windowspath(' :/users/al/desktop/calc exe')windowspath(' :/users/aldesktop/foo txt')--snip-windowspath(' :/users/al/desktop/zzz txt')the glob expression '? ?will return files with any name and any three-character extension where the middle character is an 'xby picking out files with specific attributesthe glob(method lets you easily specify the files in directory you want to perform some operation on you can use for loop to iterate over the generator that glob(returnsp path(' :/users/al/desktop'for textfilepathobj in glob('txt')print(textfilepathobjprints the path object as string do something with the text file :\users\al\desktop\foo txt :\users\al\desktop\spam txt :\users\al\desktop\zzz txt if you want to perform some operation on every file in directoryyou can use either os listdir(por glob('*'checking path validity many python functions will crash with an error if you supply them with path that does not exist luckilypath objects have methods to check whether given path exists and whether it is file or folder assuming that variable holds path objectyou could expect the following calling exists(returns true if the path exists or returns false if it doesn' exist calling is_file(returns true if the path exists and is fileor returns false otherwise |
2,698 | calling is_dir(returns true if the path exists and is directoryor returns false otherwise on my computerhere' what get when try these methods in the interactive shellwindir path(' :/windows'notexistsdir path(' :/this/folder/does/not/exist'calcfile path(' :/windows /system /calc exe'windir exists(true windir is_dir(true notexistsdir exists(false calcfile is_file(true calcfile is_dir(false you can determine whether there is dvd or flash drive currently attached to the computer by checking for it with the exists(method for instanceif wanted to check for flash drive with the volume named :on my windows computeri could do that with the followingddrive path(' :/'ddrive exists(false oopsit looks like forgot to plug in my flash drive the older os path module can accomplish the same task with the os path exists(path)os path isfile(path)and os path isdir(pathfunctionswhich act just like their path function counterparts as of python these functions can accept path objects as well as strings of the file paths the file reading/writing process once you are comfortable working with folders and relative pathsyou'll be able to specify the location of files to read and write the functions covered in the next few sections will apply to plaintext files plaintext files contain only basic text characters and do not include fontsizeor color information text files with the txt extension or python script files with the py extension are examples of plaintext files these can be opened with windows' notepad or macos' textedit application your programs can easily read the contents of plaintext files and treat them as an ordinary string value binary files are all other file typessuch as word processing documentspdfsimagesspreadsheetsand executable programs if you open binary reading and writing files |
2,699 | figure - figure - the windows calc exe program opened in notepad since every different type of binary file must be handled in its own waythis book will not go into reading and writing raw binary files directly fortunatelymany modules make working with binary files easier--you will explore one of themthe shelve modulelater in this the pathlib module' read_text(method returns string of the full contents of text file its write_text(method creates new text file (or overwrites an existing onewith the string passed to it enter the following into the interactive shellfrom pathlib import path path('spam txt' write_text('helloworld!' read_text('helloworld!these method calls create spam txt file with the content 'helloworld!the that write_text(returns indicates that characters were written to the file (you can often disregard this information the read_text(call reads and returns the contents of our new file as string'helloworld!keep in mind that these path object methods only provide basic interactions with files the more common way of writing to file involves using the open(function and file objects there are three steps to reading or writing files in python call the open(function to return file object call the read(or write(method on the file object close the file by calling the close(method on the file object we'll go over these steps in the following sections |
Subsets and Splits