1 / 32

Strings

Strings. Victor Norman CS104 Calvin College. Reading Quiz. Counts toward your grade. Question 1. What is printed by the following statements? s = “python” t = “rocks” print(s + t). Question 2. What is printed by the following statements? s = “python rocks” print(s[2] + s[-5]).

adrian-goff
Download Presentation

Strings

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. Strings Victor Norman CS104 Calvin College

  2. Reading Quiz • Counts toward your grade.

  3. Question 1 What is printed by the following statements? s = “python” t = “rocks” print(s + t)

  4. Question 2 What is printed by the following statements? s = “python rocks” print(s[2] + s[-5])

  5. Question 3 What is printed by the following statements? s = “python rocks” print(s[3:8])

  6. Collection Data Type • a data type that consists of multiple “smaller” data items. • aka “composite data type”. • items may have to be one type or may be of multiple types. Data may be ordered or not. • string: each item is a single character. Ordered. • list: items may be any type. Ordered. • dictionary: items may be any type. Unordered. • objects: any type. Unordered.

  7. String Type • consists of multiple characters, in order. • may be empty: “” • is immutable: • Cannot be changed once it is created. • Any string methods that seem like they may be changing the string mustbe returning a new string. • newName = name.capitalize() # returns new str, name unchanged

  8. String Operations • +: concatenates two strings to make a new string. E.g., newStr = oldStr1 + oldStr2 • []: indexing/subscripting: stringname[index]. • index from 0 to n – 1. • result is a new string (of length 1). • upper(), lower(), strip() • produce new strings.

  9. Come on and Click! What is the value of s after the following? s = ’abc’ s = ’d’ * 3 + s s = s + ’’ * 3 s = s + ’q’

  10. CQ 2 What is the value of s after this code is executed? s = “What is your name?” s.upper()

  11. Slicing Operation • Syntax and operation similar to indexing, but results in shorter new string derived from the original. • indexing: result string length is 1. • slicing: result string length may be > 1. • somestring[n:m:s] • start at character n in somestring. • go up to but not including character m. • by step s. • no n  beginning; no m  end; no s  1.

  12. Comparing Strings • use == or !=. • can compare with <, >, etc.., but really not used very often.

  13. Put on your red shoes and click the blues CQ 1: What is the output of this code? sketch = “argument clinic” print(sketch[7:-1])

  14. CQ 2 What does t hold? s = “Knights of Ni!” t = s[:]

  15. CQ 3 What does t hold? s = “Knights of Ni!” t = s[::-1]

  16. Item-based vs Index-based Iteration • item-based: for <item> in <sequence>: • <item> is each item in the sequence. • index-based: for <idx> in range(len(<sequence>)): • code in the body has the index of what item to deal with, as someSeq[idx]).

  17. Examples of each • Item-based for cheese in cheeses: print(cheese) • Index-based for idx in range(len(cheeses)): print(cheeses[idx])

  18. When to use which? • Item-based: • simpler syntax, easier to read. • use when code does not need to know where the item is in the sequence. • Index-based: • harder to read. • accessing the item is more complicated (using indexing operator). • code can know where the item is in the sequence. • code can access other items around the item.

  19. Example • What if we want to print out the cheeses like this: • Cheddar • Gouda • Venezuelan Beaver Cheese Need to use index-based:

  20. Example continued for idx in range(len(cheeses)): # idx starts at 0, but we want to # print out as if indices start at 1, # so add 1. print(str(idx + 1) + “.”, cheeses[idx])

  21. Accumulator Pattern resStr = “” # initialize var to empty or 0 for ch in someStr: # for each item if isConsonant(ch): resStr = resStr + ch # add to result • Used item-based, because didn’t care about where we were in the string. • someStr is a sequence, so syntax is legal. • results accumulated in resStr

  22. Whiteboard/IDLE Activity Write the following function that returns a string that is the same as s except that spaces are removed. defremove_spaces(s):

  23. Whiteboard/IDLE Activity Write the following function that returns a string that is the same as s except that spaces are removed. defremove_spaces(s): resStr = “” for ch in s: if ch != “ “: resStr = resStr + ch return resStr

  24. while Loop vs Index-Based for Loop for i in range(len(s)): code here uses s[i] i = 0 while i < len(s): use s[i] i = i + 1 # better: i += 1

  25. in and not in • very useful for searching a string to see if string is in the string or not. • returns Boolean: so you know if the target is in the string, but don’t know where. if “wherefore” in hamletText: print(“art thou”)

  26. Optional Parameters • Terminology: • parameters may be optional in the call. • in function definition, optional params • must appear on the end of the parameter list. • indicated by being given a default value. • Code in the function is exactly the same.

  27. Examples def weird(a, b, c=3): return a + b + c print(weird(3, 7)) print(weird(3, 7, 44)) def weirder(a=3, b=4, c=5): return a + b + c print(weirder()) print(weirder(7)) print(weirder(7, 8)) print(weirder(7, 8, 9))

  28. Examples def something(a, b, debug=False): res = a + b if debug: print(“something returning “ + res) return res x = something(44, -10) x = something(44, -10, True) # turn on debugging

  29. Activity Write a function that removes certain letters from a given string. If no letters are given, it removes all vowels (not including y). You can assume everything is lowercase. The result is returned. defremove_chars(s, <stuff>): # remove from s

  30. Activity Write a function that removes certain letters from a given string. If no letters are given, it removes all vowels (not including y). You can assume everything is lowercase. The result is returned. defremove_chars(s, ch2rem=“aeiou”): res = “” for ch in s: if ch not in ch2rem: res = res + ch return res

  31. Activity continued Given a string s, write code to call your function on s to remove all vowels. Then, write a function call to remove all letters from a to f, inclusive. Print the results. print(remove_chars(“Monty Python”)) # should print MntyPythn print(remove_chars(“Monty Python”, “My”)) # should print ontPthon

  32. Assignment • LOTS of CodeLab questions about strings. • Very good practice.

More Related