1 / 29

Chapter 4

Chapter 4. Strings. String data type. Just like integers, long integers, and floats, there is a string data type to hold strings of characters

hyman
Download Presentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 Strings

  2. String data type • Just like integers, long integers, and floats, there is a string data type to hold strings of characters • When declaring and initializing a string variable, we need to use either double quotes myStr = “Muncie rules!” or single quotesmyStr = ‘No, Boise rules!’

  3. Getting strings from the user • We saw before that input() can be used to get input from the user, as inquantity = input(“Please enter the quantity you want to buy: “) • But this won’t work with strings, like:name = input(“please enter your name: “)because Python can only recognize strings through quotation marks [single OR double] • Fortunately there is another built-in function which can get strings from the user:name = raw_input(“Please enter your name: “)

  4. Indexing • When you (or the user) creates a string in Python, it’s automatically indexed… that is, the computer starts counting at the first letter and continues to the end of the string. But the counting always starts at 0! • >>>slogan = “Python bad”

  5. Indexing, cont. • You can access individual characters by putting the index number in square brackets following the variable name. So>>>slogan = “Python bad”>>>slogan[7]‘b’

  6. Slicing • “Slicing” allows you to extract a substring from a string. • To extract “bad” from our string “Python bad”, we enter: >>>slogan = “Python bad”>>>slogan[7:10]>>>’bad’ • Notice that we had to go “off-index,” to 10, to catch the last letter. The slicing only works UP TO the last index number. So>>>slogan[7:9]>>>’ba’

  7. Concatenation • You can attach (or concatenate) two strings using the concatenation operator, which irritatingly enough looks just like the addition operator: + • >>>”Python is not only bad, “ + “it is evil.”>>>‘Python is not only bad, it is evil.’ • Notice that I added a space after the comma so the sentence, when concatenated, would look OK. Otherwise, “it” would be crammed up against the comma.

  8. Repetition • You can repeat strings (concatenate the same string to itself multiple times) by, well, just multiplying it. Weird. • >>>”Python “ * 3>>>’Python Python Python’ • Not sure when you would want to do this.

  9. Length of the string • Another useful function is finding the length of the string. (And we know it’s a function because of the parentheses.) len() • Remember >>>slogan = “Python bad” • When we enter >>>len(slogan)we’ll get10 • Huh? Shouldn’t we get 9? • The answer is that, since it’s a computer, it indexes from 0 but counts the number of units (characters) as we would—from 1. • So the LENGTH of a string is the index of the string + 1

  10. Iteration through the string • We can also process the string automatically, letter by letter. To work through our slogan string, we type>>>for char in slogan:…print charPythonbad

  11. Workshop • A palindrome is a word that, when reversed, looks exactly the same. Examples: radar, racecar, deed, civic, level, madam…. • Get a string from the user. Then reverse the string. Display both the original string and the reversed string. • TIP ONE: Strings are immutable! You can’t change them. However, you can transform a string into a list, which is mutable. To transform a string: list(str)

  12. Workshop, cont. • And just to help you out further with Tip One, remember the join(list) function concatenates a list of strings into one string • TIP TWO: Stride notation is a way of slicing a string by increments through the index. Example: • >>>Str = “Election Day” • >>>print Str[::2] • >>>Eeto a • In this case, every second letter in the string has been printed.

  13. Workshop: >>>import username • # username.py • # Simple string processing program to generate usernames. • def main(): • print "This program generates computer usernames." • print • # get user's first and last names • first = raw_input("Please enter your first name (all lowercase): ") • last = raw_input("Please enter your last name (all lowercase): ") • # concatenate first initial with 7 chars of the last name. • uname = first[0] + last[:7] • # output the username • print "Your username is:", uname • main() • ALTER THIS CODE SO THE USER ENTERS HIS/HER FULL NAME ONCE

  14. # month.py # A program to print the abbreviation of a month, given its number def main(): # months is used as a lookup table months = "JanFebMarAprMayJunJulAugSepOctNovDec" n = input("Enter a month number (1-12): ") # compute starting position of month n in months pos = (n-1) * 3 # Grab the appropriate slice from months monthAbbrev = months[pos:pos+3] # print the result print "The month abbreviation is", monthAbbrev + "." main()

  15. Lists • Lists in Python are pretty much what they sound like—a list of items. They can be declared and initialized just like any variable. • A_list_of_strings = [“Bud”, “Coors”, “Miller”] • A_list_of_integers = [1, 3, 5, 7, 9] • A_list_of_floats = [3.3, 6.6, 9.9, 11.11] • A_mixed_list = [“Pepsi”, 12.0, 6]

  16. More Lists • Lists can be repeated:>>>A_list_of_integers * 2>>>[1, 3, 5, 7, 9, 1, 3, 5, 7, 9] • Lists can be concatenated:>>> A_list_of_integers + A_mixed_list>>>[1, 3, 5, 7, 9, “Pepsi”, 12.0, 6] • Lists can be indexed: • >>> A_list_of_integers[3]>>>7 • Lists can be sliced:>>> A_list_of_integers[2:3]>>>[5, 7]

  17. # month2.py # A program to print the month name, given it's number. # This version uses a list as a lookup table. def main(): # months is a list used as a lookup table months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] n = input("Enter a month number (1-12): ") print "The month abbreviation is", months[n-1] + "." main()

  18. ASCII • ASCII refers to American Standard Code for Information Interchange—it provides a standard numerical table for typical keyboards. • 0-127 • Lowercase letters: 97-122; uppercase 65-90 • Python supports two functions which either return the numerical value of a letter or the letter corresponding to a number: ord() returns the number for a letter; chr() gives the letter corresponding to a number • Unicode is a much larger standard which has numbers corresponding to most language symbols

  19. Workshop: in pairs • Write a program which prints all the letters and their corresponding ASCII code, but make it readable: one letter and one ASCII number on a line • Hints:No user input is neededYou’ll need to use a definite loop (modify a line in chaos.py) that goes to 127To print on one line, add a comma after the print statementMany of the early numbers are “blank”—they correspond to keyboard controls like <return> or space

  20. The String library • The string library, like the math library, has many built-in functions that are useful in manipulating strings—and we don’t have to write new programs to do the things the built-in functions do • To access the string library functions, type import string • >>>family = “John, Mary, Jane”>>>string.split(family, “,”)>>>string.split(family)The last two lines produce exactly the same results.

  21. The eval() function • The eval() built-in Python function takes a string and evaluates it as a Python expression • So, it will evaluate strings as numerical expressions • >>>eval(“8 + 6”)14

  22. Most important string functions. Assume s is an actual string, like “Hello World”

  23. # dateconvert.py # Converts a date in form "mm/dd/yyyy" to "month day, year" import string def main(): # get the date dateStr = raw_input("Enter a date (mm/dd/yyyy): ") # split into components monthStr, dayStr, yearStr = string.split(dateStr, "/") # convert monthStr to the month name months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] monthStr = months[int(monthStr)-1] # output result in month day, year format print "The converted date is:", monthStr, dayStr+",", yearStr main()

  24. String formatting • The % operator, when used with strings, is a string formatting operator. • The generic form is: <template_string> % (<values>) • Expanding this:%<width>.<precision><type> & (<values<) • print “the total is: $%0.2f” % (total) Variable to be formatted Operator indicates which variable will be formatted Specifies how many spaces to use in displaying Specifies how many digits after the decimal point Specifies number type: f=float

  25. Reading files • Often we want to open a file stored on a disk and process it in our Python program. To open a file, we have to associate it with a variable in our program. • The open() built-in fuction has two parameters, the file name and whether you want to just read the file or write to it (change it). • >>>input_file = open(“list_names”, “r”)

  26. Reading files • There are three read functions in Python: • <filevar>.read(): returns the entire file as one long string • <filevar>.readline(): returns the next line of the file, as marked by newline characters • <filevar.readlines(): returns a list of the lines in the file; each line is a list item

  27. Workshop • Using the names.dat file, copy printfile.py into your text editor and try it

  28. Workshop • Copy username.py into your text editor, save it, and run it. Create a new text file with the names of your family members, or pets, or buddies, and use this as your infile.

  29. Workshop • Create a program that will take a phrase from the user and turn it into an acronym, all caps. • An acronym is the first letter from each word in a phrase: e.g., human computer interaction = HCI. • Hint: you’ll need to import the string library. The critical function/method is string.join(s); find out its parameters and output • Hint: you’ll have to use a definite loop

More Related