What are two ways to remove values from a list? Name a few ways that list values are similar to string values. What is the difference between lists and tuples? How do you type the tuple value that has just the integer value 42 in it?
How can you get the tuple form of a list value? How can you get the list form of a tuple value? What do they contain instead? What is the difference between copy. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. The 0, 0 origin will be in the upper-left corner, the x-coordinates increase going right, and w the y-coordinates increase going down.
Copy the previous grid value, and write code that uses it to print the image. Hint: You will need to use a loop in a loop in order to print grid[0][0], then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. This will finish the first row, so then print a newline. Then your program should print grid[0][1], then grid[1][1], then grid[2] [1], and so on. The last thing your program will print is grid[8][5]. Dictionaries and Structuring Data In this chapter, I will cover the dictionary data type, which provides a flexible way to access and organize data.
The Dictionary Data Type Like a list, a dictionary is a collection of many values. But unlike indexes for lists, indexes for dictionaries can use many different data types, not just integers. Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair. The values for these keys are 'fat', 'gray', and 'loud', respectively. Lists Unlike lists, items in dictionaries are unordered. The first item in a list named spam would be spam[0].
While the order of items matters for determining whether two lists are the same, it does not matter in what order the key- value pairs are typed in a dictionary. You can use a dictionary with the names as keys and the birthdays as values.
Save it as birthdays. When you run this program, it will look like this: Enter a name: blank to quit Alice Apr 1 is the birthday of Alice Enter a name: blank to quit Eve I do not have birthday information for Eve What is their birthday? Dec 5 Birthday database updated. Enter a name: blank to quit Eve Dec 5 is the birthday of Eve Enter a name: blank to quit Of course, all the data you enter in this program is forgotten when the program terminates.
The values returned by these methods are not true lists: They cannot be modified and do not have an append method. If you want a true list from one of these methods, pass its list-like return value to the list function. You can also use the multiple assignment trick in a for loop to assign the key and value to separate variables.
You can also use these operators to see whether a certain key or value exists in a dictionary. Fortunately, dictionaries have a get method that takes two arguments: the key of the value to retrieve and a fallback value to return if that key does not exist. The first argument passed to the method is the key to check for, and the second argument is the value to set at that key if the key does not exist. The method returns the value 'black' because this is now the value set for the key 'color'.
When spam. The setdefault method is a nice shortcut to ensure that a key exists. Here is a short program that counts the number of occurrences of each letter in a string. Open the file editor window and enter the following code, saving it as characterCount. This program will work no matter what string is inside the message variable, even if the string is millions of characters long!
This is helpful when you want a cleaner display of the items in a dictionary than what print provides. Modify the previous characterCount. If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.
These two lines are equivalent to each other: pprint. Each player would set up a chessboard at their home and then take turns mailing a postcard to each other describing each move. To do this, the players needed a way to unambiguously describe the state of the board and their moves. In algebraic chess notation, the spaces on the chessboard are identified by a number and letter coordinate, as in Figure The coordinates of a chessboard in algebraic chess notation The chess pieces are identified by letters: K for king, Q for queen, R for rook, B for bishop, and N for knight.
Describing a move uses the letter of the piece and the coordinates of its destination. A pair of these moves describes what happens in a single turn with white going first ; for instance, the notation 2.
Nf3 Nc6 indicates that white moved a knight to f3 and black moved a knight to c6 on the second turn of the game. Your opponent can even be on the other side of the world! Computers have good memories. A program on a modern computer can easily store billions of strings like '2. Nf3 Nc6'. This is how computers can play chess without having a physical chessboard. They model data to represent a chessboard, and you can write code to work with this model. This is where lists and dictionaries can come in.
You can use them to model real-world things, like chessboards. To represent the board with a dictionary, you can assign each slot a string-value key, as shown in Figure You can use a dictionary of values for this. The string value with the key 'top-R' can represent the top-right corner, the string value with the key 'low-L' can represent the bottom-left corner, the string value with the key 'mid-M' can represent the middle, and so on.
The slots of a tic-tactoe board with their corresponding keys This dictionary is a data structure that represents a tic-tac-toe board. Store this board-as-a- dictionary in a variable named theBoard. Open a new file editor window, and enter the following source code, saving it as ticTacToe. An empty tic-tac-toe board Since the value for every key in theBoard is a single-space string, this dictionary represents a completely clear board.
Player O wins. Of course, the player sees only what is printed to the screen, not the contents of variables. Make the following addition to ticTacToe. You could have organized your data structure differently for example, using keys like 'TOP-LEFT' instead of 'top-L' , but as long as the code works with your data structures, you will have a correctly working program.
For example, the printBoard function expects the tic-tac-toe data structure to be a dictionary with keys for all nine slots. If the dictionary you passed was missing, say, the 'mid-L' key, your program would no longer work. Modify the ticTacToe. Move on which space? Nested Dictionaries and Lists Modeling a tic-tac-toe board was fairly simple: The board needed only a single dictionary value with nine key-value pairs.
As you model more complicated things, you may find you need dictionaries and lists that contain other dictionaries and lists. Lists are useful to contain an ordered series of values, and dictionaries are useful for associating keys with values. The totalBrought function can read this data structure and calculate the total number of an item being brought by all the guests.
If it does not exist as a key, the get method returns 0 to be added to numBrought. But realize that this same totalBrought function could easily handle a dictionary that contains thousands of guests, each bringing thousands of different picnic items.
Then having this information in a data structure along with the totalBrought function would save you a lot of time! You can model things with data structures in whatever way you like, as long as the rest of the code in your program can work with the data model correctly.
Summary You learned all about dictionaries in this chapter. Lists and dictionaries are values that can contain multiple values, including other lists and dictionaries. Dictionaries are useful because you can map one item the key to another the value , as opposed to lists, which simply contain a series of values in order. Values inside a dictionary are accessed using square brackets just as with lists. Instead of an integer index, dictionaries can have keys of a variety of data types: integers, floats, strings, or tuples.
You saw an example of this with a tic-tac-toe board. That just about covers all the basic concepts of Python programming!
These modules, written by other programmers, provide functions that make it easy for you to do all these things. What does the code for an empty dictionary look like? What does a dictionary value with a key 'foo' and a value 42 look like?
What is the main difference between a dictionary and a list? If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam. What is a shortcut for the following code? Fantasy Game Inventory You are creating a fantasy video game. The addToInventory function should return a dictionary that represents the updated inventory.
Note that the addedItems list can contain multiples of the same item. Manipulating Strings Text is one of the most common forms of data your programs will handle. You can extract partial strings from string values, add or remove spacing, convert letters to lowercase or uppercase, and check that strings are formatted correctly. You can even write Python code to access the clipboard for copying and pasting text.
String Literals Typing string values in Python code is fairly straightforward: They begin and end with a single quote. But then how can you use a quote inside a string? Typing 'That is Alice's cat. Fortunately, there are multiple ways to type strings. Double Quotes Strings can begin and end with double quotes, just as they do with single quotes.
One benefit of using double quotes is that the string can have a single quote character in it. Escape Characters An escape character lets you use characters that are otherwise impossible to put into a string. Despite consisting of two characters, it is commonly referred to as a singular escape character. You can use this inside a string that begins and ends with single quotes. Table lists the escape characters you can use. How are you? I'm doing fine.
Raw Strings You can place an r before the beginning quotation mark of a string to make it a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string. Because this is a raw string, Python 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 backslashes, such as the strings used for regular expressions described in the next chapter. A multiline string in Python begins and ends with either three single quotes or three double quotes.
Open the file editor and write the following: print '''Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob''' Save this program as catnapping. The output will look like this: Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob Notice that the single quote character in Eve's does not need to be escaped.
Escaping single and double quotes is optional in raw strings. The following is perfectly valid Python code: """This is a test Python program. Written by Al Sweigart al inventwithpython. You can think of the string 'Hello world! If you specify a range from one index to another, the starting index is included and the ending index is not. The substring you get from spam[] will include everything from spam[0] to spam[4], leaving out the space at index 5. Note that slicing a string does not modify the original string.
You can capture a slice from one variable in a separate variable. 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 a Boolean True or False. Useful String Methods Several string methods analyze strings or create transformed string values. The upper , lower , isupper , and islower String Methods The upper and lower string methods return a new string where all the letters in the original string have been converted to uppercase or lower-case, respectively.
Nonletter characters in the string remain unchanged. If you want to change the original string, you 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 just like if a variable eggs contains the value The upper and lower methods are helpful if you need to make a case-insensitive comparison.
The strings 'great' and 'GREat' are not equal to each other. Adding code to your program to handle variations or mistakes in user input, such as inconsistent capitalization, will make your programs easier to use and less likely to fail. GREat I feel great too. The isupper and islower methods will return a Boolean True value if the string has at least one letter and all the letters are uppercase or lowercase, respectively.
Otherwise, the method returns False. Expressions that do this will look like a chain of method calls. These methods return a Boolean value that describes the nature of the string.
Here are some common isX string methods: isalpha returns True if the string consists only of letters and is not blank. For example, the following program repeatedly asks users for their age and a password until they provide valid input.
Open a new file editor window and enter this program, saving it as validateInput. If age is a valid decimal value, we break out of this first while loop and move on to the second, which asks for a password. Otherwise, we inform the user that they need to enter a number and again ask them to enter their age. Enter your age: 42 Select a new password letters and numbers only : secr3t! Passwords can only have letters and numbers.
Here, these tests help us reject the input forty two and accept 42, and reject secr3t! The startswith and endswith String Methods The startswith and endswith methods return True if the string value they are called on begins or ends respectively with the string passed to the method; otherwise, they return False. The join and split String Methods The join method is useful when you have a list of strings that need to be joined together into a single string value.
The returned string is the concatenation of each string in the passed-in list. Remember that join is called on a string value and is passed a list value. These whitespace characters are not included in the strings in the returned list. You can pass a delimiter string to the split method to specify a different string to split upon. I am fine. There is a container in the fridge that is labeled "Milk Experiment". Please do not drink it. Justifying Text with rjust , ljust , and center The rjust and ljust string methods return a padded version of the string they are called on, with spaces inserted to justify the text.
The first argument to both methods is an integer length for the justified string. An optional second argument to rjust and ljust will specify a fill character other than a space character. Open a new file editor window and enter the following code, saving it as picnicTable. In picnicItems, we have 4 sandwiches, 12 apples, 4 cups, and cookies.
We want to organize this information into two columns, with the name of the item on the left and the quantity on the right. To do this, we decide how wide we want the left and right columns to be. Then, it loops through the dictionary, printing each key-value pair on a line with the key justified left and padded by periods, and the value justified right and padded by spaces.
After defining printPicnic , we define the dictionary picnicItems and call printPicnic twice, passing it different widths for the left and right table columns. When you run this program, the picnic items are displayed twice. The first time the left column is 12 characters wide, and the right column is 5 characters wide. The second time they are 20 and 6 characters wide, respectively. Removing Whitespace with strip , rstrip , and lstrip Sometimes you may want to strip off whitespace characters space, tab, and newline from the left side, right side, or both sides of a string.
The strip string method will return a 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 ends, respectively. The order of the characters in the string passed to strip does not matter: strip 'ampS' will do the same thing as strip 'mapS' or strip 'Spam'. Sending the output of your program to the clipboard will make it easy to paste it to an email, word processor, or some other software.
Pyperclip does not come with Python. To install it, follow the directions for installing third-party modules in Appendix A. Fortunately, there are shortcuts you can set up to make running Python scripts easier. Turn to Appendix B 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 IDLE. Project: Password Locker You probably have accounts on many different websites. From here on, each chapter will have projects that demonstrate the concepts covered in the chapter. The projects are written in a style that takes you from a blank file editor window to a full, working program.
This way, the user can have long, complicated passwords without having to memorize them. Open a new file editor window and save the program as pw. You need to start the program with a!
The dictionary will be the data structure that organizes your account and password data. Make your program look like the following:! See Appendix B for more information on how to use command line arguments in your programs.
The first item in the sys. For this program, this argument is the name of the account whose password you want. Since the command line argument is mandatory, you display a usage message to the user if they forget to add it that is, if the sys. But a variable named account is much more readable than something cryptic like sys. If the account name is a key in the dictionary, we get the value corresponding to that key, copy it to the clipboard, and print a message saying that we copied the value.
Using the instructions in Appendix B for launching command line programs easily, you now have a fast way to copy your account passwords to the clipboard. But you can modify this program and use it to quickly copy regular text to the clipboard.
Say you are sending out several emails that have many of the same stock paragraphs in common. For more about batch files, see Appendix B. Type the following into the file editor and save the file as pw. Project: Adding Bullets to Wiki Markup When editing a Wikipedia article, you can create a bulleted list by putting each list item on its own line and placing a star in front.
But say you have a really large list that you want to add bullet points to. You could just type those stars at the beginning of each line, one by one. Or you could automate this task with a short Python script.
The bulletPointAdder. Paste text from the clipboard 2. Do something to it 3. Copy the new text to the clipboard That second step is a little tricky, but steps 1 and 3 are pretty straightforward: They just involve the pyperclip. Enter the following, saving the program as bulletPointAdder. The next step is to actually implement that piece of the program. You want to add a star to the start of each of these lines.
But it would be easier to use the split method to return a list of strings, one for each line in the original string, and then add the star to the front of each string in the list. We store the list in lines and then loop through the items in lines.
For each line, we add a star and a space to the start of the line. Now each string in lines begins with a star. Step 3: Join the Modified Lines The lines list now contains modified lines that start with stars. But pyperclip. Now the program is complete, and you can try running it with text copied to the clipboard. Whatever your needs, you can use the clipboard for input and output. Summary Text is a common form of data, and Python comes with many helpful string methods to process the text stored in string values.
You will make use of indexing, slicing, and string methods in almost every Python program you write. However, the user can quickly enter large amounts of text through the clipboard. This ability provides a useful avenue for writing programs that manipulate massive amounts of text. These text-based programs might not have flashy windows or graphics, but they can get a lot of useful work done quickly. Another way to manipulate large amounts of text is reading and writing files directly off the hard drive.
What are escape characters? The string value "Howl's Moving Castle" is a valid string. What string methods can you use to right-justify, left-justify, and center a string?
How can you trim whitespace characters from the beginning or end of a string? Practice Project For practice, write a program that does the following. Table Printer Write a function named printTable that takes a list of lists of strings and displays it in a well-organized table with each column right-justified.
Assume that all the inner lists will contain the same number of strings. You can store the maximum width of each column as a list of integers. That way, colWidths[0] can store the width of the longest string in tableData[0], colWidths[1] can store the width of the longest string in tableData[1], and so on.
You can then find the largest value in the colWidths list to find out what integer width to pass to the rjust string method. Part II. Regular expressions go one step further: They allow you to specify a pattern of text to search for.
This is how you, as a human, know a phone number when you see it: is a phone number, but 4,,, is not. Regular expressions are helpful, but not many non-programmers know about them even though most modern text editors and word processors, such as Microsoft Word or OpenOffice, have find and find-and-replace features that can search based on regular expressions. Regular expressions are huge time-savers, not just for software users but also for programmers.
You know the pattern: three numbers, a hyphen, three numbers, a hyphen, and four numbers. Open a new file editor window and enter the following code; then save the file as isPhoneNumber. If any of these checks fail, the function returns False. Calling isPhoneNumber with the argument '' will return True. Calling isPhoneNumber with 'Moshi moshi' will return False; the first test fails because 'Moshi moshi' is not 12 characters long. You would have to add even more code to find this pattern of text in a larger string.
Sign up Log in. Web icon An illustration of a computer application window Wayback Machine Texts icon An illustration of an open book. Books Video icon An illustration of two cells of a film strip. Video Audio icon An illustration of an audio speaker. Audio Software icon An illustration of a 3. Shows how to write programs that can automatically download web pages and parse them for information. This is called web scraping. This is helpful when the number of documents you have to analyze is in the hundreds or thousands.
Covers programmatically reading Word and PDF documents. Explains how time and dates are handled by Python programs and how to schedule your computer to perform tasks at certain times. This chapter also shows how your Python programs can launch non-Python programs. Explains how to write programs that can send emails and text messages on your behalf. Explains how to programmatically control the mouse and keyboard to automate clicks and keypresses.
Be sure to download a version of Python 3 such as 3. The programs in this book are written to run on Python 3 and may not run correctly, if at all, on Python 2. If you bought your computer in or later, it is most likely a bit system. If it says anything else including Intel Core 2 Duo , you have a bit machine. On Ubuntu Linux, open a Terminal and run the command uname -m. On Windows, download the Python installer the filename will end with. Follow the instructions the installer displays on the screen to install Python, as listed here:.
Select Install for All Users and then click Next. Install to the C:Python34 folder by clicking Next. On Mac OS X, download the. When the DMG package opens in a new window, double-click the Python.
You may have to enter the administrator password. Click Continue through the Welcome section and click Agree to accept the license. Select HD Macintosh or whatever name your hard drive has and click Install. This window is called the interactive shell. A shell is a program that lets you type instructions into the computer, much like the Terminal or Command Prompt on OS X and Windows, respectively. The computer reads the instructions you enter and runs them immediately. Solving programming problems on your own is easier than you might think.
But keep in mind there are smart ways to ask programming questions that help others help you. Be sure to read the Frequently Asked Questions sections these websites have about the proper way to post questions. In Automate the Boring Stuff with Python , you'll learn how to use Python to write programs that do in minutes what would take you hours to do by hand - no prior programming experience required.
Once you've mastered the basics of programming, you'll create Python programs that effortlessly perform useful and impressive feats of automation to:. Step-by-step instructions walk you through each program, and practice projects at the end of each chapter challenge you to improve those programs and use your newfound skills to automate similar tasks.
Don't spend your time doing work a well-trained monkey could do. Even if you've never written a line of code, you can make your computer do the grunt work.
0コメント