Strings
Jake Shoudy
Aug 29, 2022
CSCI 110 - Lecture 8
Today’s Agenda
|
|
| |
| |
| |
| |
Announcements
Pre-class Surveys
Two surveys posted on Ed
Please take them 🙏 🙏 🙏
Google TechExchange
What: Google program for HBCU students to learn CS things on Google campus (targeted at sophomores)
Google program leads will be on Fisk Campus to talk about it!
Timing: Aug 29th 2022 (today!), 5-7pm See more here
HW 1 Scores
| Score |
Mean | 84% |
Min | 10% |
Max | 100% |
Median | 93% |
Percent of class above 70% | 85% |
Percent of class above 90% | 59% |
Quiz 2 Scores
| Score |
Mean | 72% |
Min | 10% |
Max | 100% |
Median | 80% |
Percent of class above 70% | 54% |
Percent of class above 90% | 20% |
Project 1: Part 2
TA Office Hours
All available on class calendar
Google 20% TAs
Missed the first 4 lectures of class? Just plain lost?
Some folks from Google are volunteering their time to help you with your computer science scoolwork!
If you feel that you are falling behind and want more 1:1 attention let me know and I will try to pair you with someone who can help!
Recap
Review: While Loops
What are they?
Control structure that runs a block of code repeatedly until a certain condition is no longer met
Why are they important?
Write code once and run many times - do not need to copy and paste same code over and over
while [expression evaluates True]:
[do stuff]
Review: Syntax
while [expression evaluates True]:
[do stuff]
This expression needs to evaluate to True to run, BUT...
Review: Syntax
while [expression evaluates True]:
[do stuff]
...also needs to be able to evaluate to False.
Review: Syntax
What happens?
count = 3
while count > 0:
print(count)
count = count - 1
print("Blast off!")
What happens? Why?
x = 1
while x < 1:
print("test")
What happens? Why?
x = 1
while x < 2:
print("test")
Infinite loops!
while True:
print("Still true")
print("This will never print")
Make sure condition includes a variable that changes in the loop body so condition eventually becomes False
Break statement
x = 1
while True:
print("test")
if x > 5:
break
x = x + 1
print("will this print?")
Better: use a good condition
x = 1
while x < 5:
print("test")
x = x + 1
print("will this print?")
Strings
Objectives: String Functions
Get string length
Index into a string to access individual characters
Get substring: part of a string
length
Strings vs Character
String: sequence of characters
'wall' '88 + 99' 'Click here.' ' '
Character: anything typed in a single keystroke, commonly known as char
'r' '8' 'A' ',' '&' ' ' '?'
What is the length of each string?
'Fisk'
':)'
'Good morning!'
'$10.99'
'2 + 2 = 5'
4
2
13
6
9
len() function
len(s): returns number of characters in given string
len('Fisk')
len(':)')
len(' ')
len('Good morning!')
indexing
Indexing
Index: position of an element in a sequence
Always start counting from index 0, which means last index is always one less than string length: len(word) - 1.
Go Bulldogs!
0
1
2
3
4
5
6
7
8
9
10
11
Indexing: Rapid fire
'Chipotle'
'Harry Potter'
'Nashville, TN'
'$4593.01'
'...what?'
C: 0, p: 3
P: 6, r: 11
a: 1, ,: 9
5: 2, 0: 6
w: 3, ?: 7
Indexing: Python Syntax
In Python, use square brackets [ ] to access character at an index
phrase = 'Welcome to Fisk University!'
phrase[0]
phrase[5]
Indexing Strings Practice
username = 'kittens27'
print(username[4])
print(username[7])
e
2
IndexError
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: string index out of range
Often referred to as Index Out of Bounds error.
word = 'frog'
print(word[8])
slicing
Slicing
Slice: subsequence of a string
In Python, use square brackets [ ] with two indices to slice a string.
phrase = 'Welcome to Fisk University!'
phrase[2:5]
Start index and end index
Character at start index is included, character at end index is excluded
If omit first index (before colon), slice starts at beginning of string
If omit second index, slice goes to end of string
Slicing Practice
name = 'Ariana Grande'
print(name[1:5])
print(name[:8])
print(name[2:])
‘rian’
‘Ariana G’
‘iana Grande’
Bonus string things
Concatenation
Sticking two parts together
Combine strings using + operator
name = "Jake"
intro = "My name is " + name
print(intro + " and I like snacks")
Format Strings
Cleaner alternative: format()
Strings inside of format() will be substituted for {} in string
name = "Jake"
intro = "My name is"
sentence = "{} {} and I like snacks".format(intro, name)
print(sentence)
Practice!
print("Hi, " + "what is your name?")
Hi, what is your name?
print("Once I {} {} servings of {}".format("ate", 94, "hotdogs"))
Once I ate 94 servings of hotdogs
print("You can {} both".format("combine") + "(but probably shouldn't)")
You can combine both (but probably shouldn’t)
Other String Functions
Pre-written functions provided by Python, like len(s)!
docs.python.org/3/library/stdtypes.html#string-methods
Built-In String Functions
What do these do?
"test".upper()
“TEST”
“example”
“some string”
“construction”
"ExAmPlE".lower()
" some string ".strip()
"destruction".replace("de", "con")
"fun in the sun".replace("un", "ire")
"fun in the sun".replace("un", "ire", 1)
“fire in the sire”
“fire in the sun”
quote = ""Let's get internships" - students"
quote = '"Let's get internships" - students'
Escaping
Some characters have special meaning, like quotes
Sometimes, need "invisible" characters, like newlines
Use escaping!
quote = "\"Let's get internships\"\n- students"
print(quote)
Escaping
\n - newline
\t - tab
\" - quotation mark
\' - apostrophe
\\ - backslash
Review: Strings
len(s): returns length of string s
string[i]: access individual characters in string for index i
string[start:end]: substring - gets string from start to end, not including end
format: replaces {} with anything
upper/lower: changes string to all upper/lower case letters
strip: removes any leading or trailing spaces from a string
replace: finds instances of the first string and replaces it with the second
escaping: use \ to signify some special meaning
Questions?