Week 7 Quiz: Strings; plus ThinkCSPY Ch. 9 Strings
for loops on strings
# Classic for loop for c in 'brian': print(c) # You can also use a few variables for i, c in enumerate(string): print(i, c)
How would you use a for loop to iterate though the indices of each character in a string? ThinkCSPY Ch9
# Use a combination of range() and len() and indexing fruit = 'apple' for c in range(len(fruit): print(fruit[idx]))
How would you iterate through a string, but go back to forward? ex. if you want to create a new string that is a REVERSE ThinkCSPY Ch9
## Use range() with arguments for start, stop, step == -1 fruit = 'apple' for i in range(len(fruit) -1, -1, -1): print(fruit[i])
Which data types are considered to be simple or 'primitive' data types? (ThinkCSPY Ch9)
'Primitive', because :they can't be broken down any further - int, - float - bool On the other hand, 'Collection data types' are made up of smaller pieces: - strings are made up of sequential characters - lists are made up of strings * Can be treated as a single entity OR broken up to access its pieces
Built in Boolean String Functions - 'in'
'str1' in 'str2' #Check if string1 is in string 2 > True 'str3' not in 'str4' #Checks if string3 is not in string4 > True
When you compare strings, how do they return Boolean values? 2 ways:
(1) Based on their ALPHABETICAL position in Unicode: fred > flint (2) Based on their LENGTH. Shorter words are less: fred < freddy
String Accumulators (2 Types)
(1) Number Accumulators: count = 0 ## Starts with a counter number for i in range(5): count += 1 (2) String Accumulators: doubles = "" ## Starts with an empty string for c in 'brian': doubles += c*2 print(doubles)
Slicing strings - a range, index [start:end:step]
* Returns a NEW string (remember, strings are immutable) Starts with start, up to but NOT including end, via step. * Default start will be 0, default stop will be the length of the string, default step is 1 Ex. string[1:6] >> 'tring' string[::2] >> 'srn' string[1::2] >> 'tig'
What is printed by the following statements: s = "ball" r = "" for item in s: r = item.upper() + r print(r) (A) Ball (B) BALL (C) LLAB ThinkCSPY Ch9
***** THE ORDER IS REVERSED DUE TO THE ORDER OF CONCATENATION******* so it's (C)- LLAB
THings you can do to strings
- Change - Shorten - Reverse - Anything
What three things is the programmer responsible for when writing good while loops? ThinkCSPY Ch9
1. Setting up the initial condition 2. Making sure the condition is correct 3. Making sure that something changes inside the body to guarantee that the condition will eventually fail
What is printed by the following statements? s = "python rocks" print(len(s)) (A) 11 (B) 12 ThinkCSPY
12 ** For len(), you literally get the length. This is not the same thing as the index.
How do you use string formatting for floats to display exactly two decimal places? (ThinkCSPY Ch9)
:.2f inside the braces print('${:.2f} discounted by{}% is ${:.2f}.'.format(origPrice, disscount,newPrice)
How many times is the letter o printed by the following statements? s = "python rocks" for idx in range(len(s)): if idx % 2 == 0: print(s[idx]) A. 0 B. 1 C. 2 D. Error, the for statement cannot have an if inside ThinkCSPY Ch9
>> pto ok so (C) It will print all the characters in even index positions.
How many times is the letter o printed by the following statements? s = "python rocks" idx = 1 while idx < len(s): print(s[idx]) idx = idx + 2 (A) 0 (B) 1 (C) 2 ThinkCSPY Ch9
>>> yhnrcs so (A)
What is printed by the following statements? s = "python rocks" print(s[7:11] * 3) (A) rockrockrock (B) rock rock rock (C) rocksrocksrocks (D) Error, you cannot use repetition with slicing. ThinkCSPY
A
What is printed? s = 'python rocks' print(s[1] * s.index('n')) (A) yyyyy (B) 55555 (C) n (D) Error, you cannot combine all those things together. (ThinkCSPY Ch9)
A
format string method 'string {}'.format() (ThinkCSPY Ch9)
A powerful string method that allows you to use braces {} to insert the exact substitutions you want person = input('Your name: ") greeting = 'Hello {}!.format(person) print(greeting) the string you want to insert is called the 'format string' if you have several format strings, just list with commas:
Evaluate the following comparison: "Dog" < "Doghouse" (A) True (B) False THINKCSPY
A. True The shorter one is lesser Boolean one
String Boolean Methods
ALL OF THESE RETURN TRUE OR FALSE. str.isalnum() # Is the string alphanumeric? str.isalpha() # Is the string alphabeticcal? str.isdigit() # Is the string all numerical? str.islower() # Is the string all lowercase? str.isupper() # Is the string all uppercase? str.isspace() # Is the string all spaces? str.startswith(substr) # Does the string start with a chr or substring? str.endswith(substr) # Does the string end with a chr or substring?
What is printed by the following statements? s = "python rocks" print(s[len(s)-5]) (A) o (B) r (C) s (D) Error, len(s) is 12 and there is no index 12. ThinkCSPY
B uses both counting length and then math then index
Evaluate the following comparison: "dog" < "Dog" (A) True (B) False (C) They are the same word ThinkCSPY
B. False
Evaluate the following comparison: "dog" < "Doghouse" ThinkCSPY
B. False just cuz it's shorter, the precedence goes to the fact that lowercase d is greater than uppercase D.
LEXICOGRAPHICAL ORDER: All uppercase letters come (before/after) lowercase letters???????
Before!
What is printed by the following statements? s = "python rocks" print(s[3:8]) (A) python (B) rocks (C) hon r (D) Error, you cannot have two numbers inside the [ ]. ThinkCSPY
C
What is printed by the following statements? x = 2 y = 6 print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y)) (A) Nothing - it causes an error (B) sum of {} and {} is {}; product: {}. 2 6 8 12 (C) sum of 2 and 6 is 8; product: 12. (D) sum of {2} and {6} is {8}; product: {12}. (ThinkCSPY)
C
strings-9-1: What is printed by the following statements: s = "Ball" s[0] = "C" print(s) (A) Ball (B) Call (C) Error
C
What is printed by the following statements? v = 2.34567 print('{:.1f} {:.2f} {:.7f}'.format(v, v, v)) (A) 2.34567 2.34567 2.34567 (B) 2.3 2.34 2.34567 (C) 2.3 2.35 2.3456700 (ThinkCSPY)
C * Note, the {:.2f} uses ROUNDING not just cutting it off!
chr(n)
Converts Unicode to character
ord(c)
Converts character to Unicode ord('a') >> 97 ord('A') >> 65
What are methods vs functions?
Functions are standalone...Methods are functions, attached to objects. In Python there's not much difference.
ordinal value aka the ord() function ThinkCSPY
Gives the lexicographical order of the letter When you compare characters or strings to one another, Python converts the characters into their equivalent ordinal values and compares the integers from left to right.
With string accumulators, what is different? ThinkCSPY Ch9
Instead of using a counter (type int), we build up a new string (type str) Instead of addition (+), we are concatenating (+)
the string you want to insert is called the 'format string' if you have several format strings, what do you do? (ThinkCSPY Ch9)
Just list with commas! origPrice = float(input("enter:")) discount = float(input("Enter %:")) newPrice = (1 - discount/100)*origPrice calculation = '${} discounted by {}% is ${}.'.format(origPrice, discount, newPrice) print(calculation)
If you want to change a string, what do you do?
Make a new string and replace the old one. >>> name = 'Fred' >>> name = name + ' Flintstone" >>> print(name) Fred Flintstone
String methods (ThinkCSPY Ch9)
Method Parameters Description upper none Returns a string in all uppercase lower none Returns a string in all lowercase capitalize none Returns a string with first character capitalized, the rest lower strip none Returns a string with the leading and trailing whitespace removed lstrip none Returns a string with the leading whitespace removed rstrip none Returns a string with the trailing whitespace removed count item Returns the number of occurrences of item replace old, new Replaces all occurrences of old substring with new center width Returns a string centered in a field of width spaces ljust width Returns a string left justified in a field of width spaces rjust width Returns a string right justified in a field of width spaces find item Returns the leftmost index where the substring item is found, or -1 if not found rfind item Returns the rightmost index where the substring item is found, or -1 if not found index item Like find except causes a runtime error if item is not found rindex item Like rfind except causes a runtime error if item is not found format substitutions Involved! See String Format Method, below
Can you perform mathematical operations on strings that look like numbers? ex. message - 1 (ThinkCSPY Ch9)
No The + operator works for strings, but it does not add--it concatenates The * operator also works too, but it spits out a triplet concatenation or whatever
What do you think fruit[:] means? ThinkCSPY
Print the whole slice!
len() ThinkCSPY
Returns the number of characters in a string
str.split()
Splits string into a LIST of words 'apples oranges bananas'.split() ['apples', 'oranges', 'bananas'] You can put various characters as arguments if you want to split on '-' or 's' or whatever
string.find(substr)
String search method Starts where the substring starts, and returns the index (# of position)
string.rfind(substr)
String search method that starts with the rightmost index of the substring Returns the index (# of position) If not found, returns -1
str.replace()
Takes two arguments: the thing you want to replace, and what you are replacing it with: 'Olivia Sucks'.replace('Sucks', 'Is Ok') 'Olivia Is Ok'
True or false: The index operator has precedence over concatenation (ThinkCSPY Ch9)
True
An empty string is a substring of any other string. True or False? ThinkCSPY Ch9
True print("" in "apple") >> True print("" in 'a') >> True
Strings are Immutable. What does that mean?
You can't assign a new character with indexing. That is, 'brian'[0] = 'B' #TypeError: 'str' object does not support item assignment
what is a str?
a type of collection - a sequence
Concatenation
adding strings
"dot notation" (ThinkCSPY Ch9)
another way to say the format of string methods 'string'.method(parameter)
string methods
anything in this format: 'stringname'.method(arguments)
characters
are strings with lengths of 1
NEVER USE THE [] SLICER ON THE LEFT SIDE OF ASSIGNMENT
bc strings are immutable
chr()
converts integers into their character equivalent character (Unicode)
'' (ThinkCSPY Ch9)
empty string
How would you construct a while loop, to iterate through a string? ThinkCSPY Ch9
fruit = 'apple' position = 0 while position < len(fruit): print(fruit[position]) position += 1 # Loop will continue as long as it's less than the length of the fruit
How would you get the index of the last character?
len(str) - 1 len('hi!') - 1 == 2
len()
returns length of # of characters in a string
Repetition of strings
s3 = 'liv' 3*s3 > 'livlivliv' 3*s3 + 'string' > 'livlivlivstring' (Note operator precedence, * before +)
type() of a string?
str
String modification methods Create a new string based on the given string
str.title() #Converts to Title Case str.lower() # Converts to lowercase str.upper() # Converts to UPPERCASE
while loops on strings
string = 'brian' i = 0 while i < len(string): print(string[i]) i += 1 # Counter to prevent infinite loop!
in and not in operators do what? ThinkCSPY Ch9
tell if one string is a substring of another: print('p' in 'apple') print('i' in 'apple') print('ap' in 'apple') print('pa' in 'apple') >> True >> False >> True >> False
indexing
to get individual characters of a string string[0] #1st character string[1] #2nd character / element string[-1] #last character /element