Adapted from John Zelle's Book Slides.ppt

上传人:Iclinic170 文档编号:378028 上传时间:2018-10-09 格式:PPT 页数:68 大小:457KB
下载 相关 举报
Adapted from John Zelle's Book Slides.ppt_第1页
第1页 / 共68页
Adapted from John Zelle's Book Slides.ppt_第2页
第2页 / 共68页
Adapted from John Zelle's Book Slides.ppt_第3页
第3页 / 共68页
Adapted from John Zelle's Book Slides.ppt_第4页
第4页 / 共68页
Adapted from John Zelle's Book Slides.ppt_第5页
第5页 / 共68页
亲,该文档总共68页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

1、Adapted from John Zelles Book Slides,1,CS177 Python Programming,Chapter 5 Sequences: Strings, Lists, and Files,Python Programming, 2/e,2,The String Data Type,Text is represented in programs by the string data type. A string is a sequence of characters enclosed within quotation marks (“) or apostroph

2、es ().,Python Programming, 2/e,3,The String Data Type, str1=“Hello“ str2=spam print(str1, str2) Hello spam type(str1) type(str2) ,Python Programming, 2/e,4,The String Data Type,Getting a string as input firstName = input(“Please enter your name: “) Please enter your name: John print(“Hello“, firstNa

3、me) Hello JohnNotice that the input is not evaluated. We want to store the typed characters, not to evaluate them as a Python expression.,Python Programming, 2/e,5,The String Data Type,We can access the individual characters in a string through indexing. The positions in a string are numbered from t

4、he left, starting with 0. The general form is , where the value of expr determines which character is selected from the string.,Python Programming, 2/e,6,The String Data Type, greet = “Hello Bob“ greet0 H print(greet0, greet2, greet4) H l o x = 8 print(greetx - 2) B,Python Programming, 2/e,7,The Str

5、ing Data Type,In a string of n characters, the last character is at position n-1 since we start counting with 0. We can index from the right side using negative indexes. greet-1 b greet-3 B,Python Programming, 2/e,8,The String Data Type,Indexing returns a string containing a single character from a

6、larger string. We can also access a contiguous sequence of characters, called a substring, through a process called slicing.,Python Programming, 2/e,9,The String Data Type,Slicing: : start and end should both be ints The slice contains the substring beginning at position start and runs up to but doe

7、snt include the position end.,Python Programming, 2/e,10,The String Data Type, greet0:3 Hel greet5:9 Bob greet:5 Hello greet5: Bob greet: Hello Bob,Python Programming, 2/e,11,The String Data Type,If either expression is missing, then the start or the end of the string are used. Can we put two string

8、s together into a longer string? Concatenation “glues” two strings together (+) Repetition builds up a string by multiple concatenations of a string with itself (*),Python Programming, 2/e,12,The String Data Type,The function len will return the length of a string. “spam“ + “eggs“ spameggs “Spam“ +

9、“And“ + “Eggs“ SpamAndEggs 3 * “spam“ spamspamspam “spam“ * 5 spamspamspamspamspam (3 * “spam“) + (“eggs“ * 5) spamspamspameggseggseggseggseggs,Python Programming, 2/e,13,The String Data Type, len(“spam“) 4 for ch in “Spam!“:print (ch, end=“ “)S p a m !,Python Programming, 2/e,14,The String Data Typ

10、e,Python Programming, 2/e,15,Simple String Processing,Usernames on a computer system First initial, first seven characters of last name# get users first and last names first = input(“Please enter your first name (all lowercase): “) last = input(“Please enter your last name (all lowercase): “)# conca

11、tenate first initial with 7 chars of last name uname = first0 + last:7,Python Programming, 2/e,16,Strings, Lists, and Sequences,It turns out that strings are really a special kind of sequence, so these operations also apply to sequences! 1,2 + 3,4 1, 2, 3, 4 1,2*3 1, 2, 1, 2, 1, 2 grades = A, B, C,

12、D, F grades0 A grades2:4 C, D len(grades) 5,Python Programming, 2/e,17,Strings, Lists, and Sequences,Strings are always sequences of characters, but lists can be sequences of arbitrary values. Lists can have numbers, strings, or both! myList = 1, “Spam “, 4, “U“,Python Programming, 2/e,18,Strings, L

13、ists, and Sequences,We can make a list of months: months = “Jan“, “Feb“, “Mar“, “Apr“, “May“, “Jun“, “Jul“, “Aug“, “Sep“, “Oct“, “Nov“, “Dec“To get the months out of the sequence, do this: monthAbbrev = monthsn-1,Python Programming, 2/e,19,Strings, Lists, and Sequences,# month2.py # A program to pri

14、nt the month name, given its number. # This version uses a list as a lookup table.def main():# months is a list used as a lookup tablemonths = “Jan“, “Feb“, “Mar“, “Apr“, “May“, “Jun“,“Jul“, “Aug“, “Sep“, “Oct“, “Nov“, “Dec“n = eval(input(“Enter a month number (1-12): “)print (“The month abbreviatio

15、n is“, monthsn-1 + “.“)main()Note that the months line overlaps a line. Python knows that the expression isnt complete until the closing is encountered.,Python Programming, 2/e,20,Strings, Lists, and Sequences,# month2.py # A program to print the month name, given its number. # This version uses a l

16、ist as a lookup table.def main():# months is a list used as a lookup tablemonths = “Jan“, “Feb“, “Mar“, “Apr“, “May“, “Jun“,“Jul“, “Aug“, “Sep“, “Oct“, “Nov“, “Dec“n = eval(input(“Enter a month number (1-12): “)print (“The month abbreviation is“, monthsn-1 + “.“)main() Since the list is indexed star

17、ting from 0, the n-1 calculation is straight-forward enough to put in the print statement without needing a separate step.,Python Programming, 2/e,21,Strings, Lists, and Sequences,This version of the program is easy to extend to print out the whole month name rather than an abbreviation! months = “J

18、anuary“, “February“, “March“, “April“, “May“, “June“, “July“, “August“, “September“, “October“, “November“, “December“,Python Programming, 2/e,22,Strings, Lists, and Sequences,Lists are mutable, meaning they can be changed. Strings can not be changed. myList = 34, 26, 15, 10 myList2 15 myList2 = 0 m

19、yList 34, 26, 0, 10 myString = “Hello World“ myString2 l myString2 = “p“Traceback (most recent call last):File “, line 1, in -toplevel-myString2 = “p“ TypeError: object doesnt support item assignment,Python Programming, 2/e,23,Strings and Character Numbers,Inside the computer, strings are represente

20、d as sequences of 1s and 0s, just like numbers. A string is stored as a sequence of binary numbers, one number per character. It doesnt matter what value is assigned as long as its done consistently.,Python Programming, 2/e,24,Strings and Character Numbers,In the early days of computers, each manufa

21、cturer used their own encoding of numbers for characters. ASCII system (American Standard Code for Information Interchange) uses 127 bit codes Python supports Unicode (100,000+ characters),Python Programming, 2/e,25,Strings and Character Numbers,The ord function returns the numeric (ordinal) code of

22、 a single character. The chr function converts a numeric code to the corresponding character. ord(“A“) 65 ord(“a“) 97 chr(97) a chr(65) A,Python Programming, 2/e,26,Other String Methods,There are a number of other string methods. Try them all! s.capitalize() Copy of s with only the first character c

23、apitalized s.title() Copy of s; first character of each word capitalized s.center(width) Center s in a field of given width,Python Programming, 2/e,27,Other String Operations,s.count(sub) Count the number of occurrences of sub in s s.find(sub) Find the first position where sub occurs in s s.join(lis

24、t) Concatenate list of strings into one large string using s as separator. s.ljust(width) Like center, but s is left-justified,Python Programming, 2/e,28,Other String Operations,s.lower() Copy of s in all lowercase letters s.lstrip() Copy of s with leading whitespace removed s.replace(oldsub, newsub

25、) Replace occurrences of oldsub in s with newsub s.rfind(sub) Like find, but returns the right-most position s.rjust(width) Like center, but s is right-justified,Python Programming, 2/e,29,Other String Operations,s.rstrip() Copy of s with trailing whitespace removed s.split() Split s into a list of

26、substrings s.upper() Copy of s; all characters converted to uppercase,Python Programming, 2/e,30,Input/Output as String Manipulation,Often we will need to do some string operations to prepare our string data for output (“pretty it up”) Lets say we want to enter a date in the format “05/24/2003” and

27、output “May 24, 2003.” How could we do that?,Python Programming, 2/e,31,Input/Output as String Manipulation,Input the date in mm/dd/yyyy format (dateStr) Split dateStr into month, day, and year strings Convert the month string into a month number Use the month number to lookup the month name Create

28、a new date string in the form “Month Day, Year” Output the new date string,Python Programming, 2/e,32,Input/Output as String Manipulation,The first two lines are easily implemented! dateStr = input(“Enter a date (mm/dd/yyyy): “) monthStr, dayStr, yearStr = dateStr.split(“/“) The date is input as a s

29、tring, and then “unpacked” into the three variables by splitting it at the slashes and using simultaneous assignment.,Python Programming, 2/e,33,Input/Output as String Manipulation,Next step: Convert monthStr into a number We can use the int function on monthStr to convert “05“, for example, into th

30、e integer 5. (int(“05“) = 5),Python Programming, 2/e,34,Input/Output as String Manipulation,Note: eval would work, but for the leading 0 int(“05“) 5 eval(“05“) Traceback (most recent call last): File “, line 1, in eval(“05“) File “, line 1 05 SyntaxError: invalid token This is historical baggage. A

31、leading 0 used to be used for base 8 (octal) literals in Python.,Python Programming, 2/e,35,Input/Output as String Manipulation,months = “January”, “February”, , “December” monthStr = monthsint(monthStr) 1 Remember that since we start counting at 0, we need to subtract one from the month. Now lets c

32、oncatenate the output string together!,Python Programming, 2/e,36,Input/Output as String Manipulation,print (“The converted date is:“, monthStr, dayStr+“,“, yearStr)Notice how the comma is appended to dayStr with concatenation! main() Enter a date (mm/dd/yyyy): 01/23/2010 The converted date is: Janu

33、ary 23, 2010,Python Programming, 2/e,37,Input/Output as String Manipulation,Sometimes we want to convert a number into a string. We can use the str function. str(500) 500 value = 3.14 str(value) 3.14 print(“The value is“, str(value) + “.“) The value is 3.14.,Python Programming, 2/e,38,Input/Output a

34、s String Manipulation,If value is a string, we can concatenate a period onto the end of it. If value is an int, what happens? value = 3.14 print(“The value is“, value + “.“) The value isTraceback (most recent call last):File “, line 1, in -toplevel-print “The value is“, value + “.“ TypeError: unsupp

35、orted operand type(s) for +: float and str,Python Programming, 2/e,39,Input/Output as String Manipulation,We now have a complete set of type conversion operations:,Python Programming, 2/e,40,String Formatting,String formatting is an easy way to get beautiful output! Change CounterPlease enter the co

36、unt of each coin type. Quarters: 6 Dimes: 0 Nickels: 0 Pennies: 0The total value of your change is 1.5 Shouldnt that be more like $1.50?,Python Programming, 2/e,41,String Formatting,We can format our output by modifying the print statement as follows: print(“The total value of your change is $0:0.2f

37、“.format(total) Now we get something like: The total value of your change is $1.50 Key is the string format method.,Python Programming, 2/e,42,String Formatting,.format() within the template-string mark “slots” into which the values are inserted. Each slot has description that includes format specif

38、ier telling Python how the value for the slot should appear.,Python Programming, 2/e,43,String Formatting,print(“The total value of your change is $0:0.2f“.format(total) The template contains a single slot with the description: 0:0.2f Form of description: : Index tells which parameter to insert into

39、 the slot. In this case, total.,Python Programming, 2/e,44,String Formatting,The formatting specifier has the form: . f means “fixed point“ number tells us how many spaces to use to display the value. 0 means to use as much space as necessary.is the number of decimal places.,Python Programming, 2/e,

40、45,String Formatting, “Hello 0 1, you may have won $2“ .format(“Mr.“, “Smith“, 10000) Hello Mr. Smith, you may have won $10000 This int, 0:5, was placed in a field of width 5.format(7) This int, 7, was placed in a field of width 5 This int, 0:10, was placed in a field of witdh 10.format(10) This int

41、, 10, was placed in a field of witdh 10 This float, 0:10.5, has width 10 and precision 5.format(3.1415926) This float, 3.1416, has width 10 and precision 5. This float, 0:10.5f, is fixed at 5 decimal places.format(3.1415926) This float, 3.14159, has width 0 and precision 5.,Python Programming, 2/e,4

42、6,String Formatting,If the width is wider than needed, numeric values are right-justified and strings are left- justified, by default. You can also specify a justification before the width. “left justification: 0: “right justification: 0:5.format(“Hi!“) right justification: Hi! “centered: 0:5“.forma

43、t(“Hi!“) centered: Hi! ,Python Programming, 2/e,47,Better Change Counter,With what we know now about floating point numbers, we might be uneasy about using them in a money situation. One way around this problem is to keep trace of money in cents using an int or long int, and convert it into dollars

44、and cents when output.,Python Programming, 2/e,48,Better Change Counter,If total is a value in cents (an int), dollars = total/100 cents = total%100 Cents is printed using width 02 to right-justify it with leading 0s (if necessary) into a field of width 2. Thus 5 cents becomes 05,Python Programming,

45、 2/e,49,Better Change Counter,# change2.py # A program to calculate the value of some change in dollars. # This version represents the total cash in cents.def main():print (“Change Countern“)print (“Please enter the count of each coin type.“)quarters = eval(input(“Quarters: “)dimes = eval(input(“Dim

46、es: “)nickels = eval(input(“Nickels: “)pennies = eval(input(“Pennies: “)total = quarters * 25 + dimes * 10 + nickels * 5 + pennies print (“The total value of your change is $0.1:02“ .format(total/100, total%100),Python Programming, 2/e,50,Better Change Counter, main() Change CounterPlease enter the

47、count of each coin type. Quarters: 0 Dimes: 0 Nickels: 0 Pennies: 1The total value of your change is $0.01, main() Change CounterPlease enter the count of each coin type. Quarters: 12 Dimes: 1 Nickels: 0 Pennies: 4The total value of your change is $3.14,Python Programming, 2/e,51,A file is a sequenc

48、e of data that is stored in secondary memory (disk drive). Files can contain any data type, but the easiest to work with are text. A file usually contains more than one line of text. Python uses the standard newline character (n) to mark line breaks.,Files: Multi-line Strings,Python Programming, 2/e

49、,52,Multi-Line Strings,Hello World Goodbye 32 When stored in a file: HellonWorldnnGoodbye 32n,Python Programming, 2/e,53,Multi-Line Strings,This is exactly the same thing as embedding n in print statements. Remember, these special characters only affect things when printed. They dont do anything during evaluation.,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 教学课件 > 大学教育

copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1