1 of 47

Strings

Jake Shoudy

Aug 29, 2022

CSCI 110 - Lecture 8

2 of 47

Today’s Agenda

  • Recap
  • String length
  • String indexing
  • String slicing

3 of 47

Announcements

4 of 47

Pre-class Surveys

Two surveys posted on Ed

Please take them 🙏 🙏 🙏

5 of 47

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

6 of 47

HW 1 Scores

Score

Mean

84%

Min

10%

Max

100%

Median

93%

Percent of class above 70%

85%

Percent of class above 90%

59%

7 of 47

Quiz 2 Scores

Score

Mean

72%

Min

10%

Max

100%

Median

80%

Percent of class above 70%

54%

Percent of class above 90%

20%

8 of 47

Project 1: Part 2

  • Actual game of blackjack! Released this morning
    • Part 2a: dealer.py
    • Part 2b: user.py
  • Solutions to part 1 available
    • Either by looking at solutions tab in part 1
    • But they’ve also been copied to part 2 starter code
  • Due on Sunday (9/4) at 11:59pm

9 of 47

TA Office Hours

  • Aminu
    • Mondays from 5-6pm (Library 3rd floor)
  • Aman
    • Mondays from 10:30-11:30am (Library 3rd floor)
  • Angel:
    • Tuesdays from 3-4pm (Library 3rd floor)
  • Arun:
    • Fridays from 9:30-10:30am (Library 3rd floor)

All available on class calendar

10 of 47

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!

11 of 47

Recap

12 of 47

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

13 of 47

while [expression evaluates True]:

[do stuff]

Review: Syntax

14 of 47

while [expression evaluates True]:

[do stuff]

This expression needs to evaluate to True to run, BUT...

Review: Syntax

15 of 47

while [expression evaluates True]:

[do stuff]

...also needs to be able to evaluate to False.

Review: Syntax

16 of 47

What happens?

count = 3

while count > 0:

print(count)

count = count - 1

print("Blast off!")

17 of 47

What happens? Why?

x = 1

while x < 1:

print("test")

18 of 47

What happens? Why?

x = 1

while x < 2:

print("test")

19 of 47

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

20 of 47

Break statement

x = 1

while True:

print("test")

if x > 5:

break

x = x + 1

print("will this print?")

21 of 47

Better: use a good condition

x = 1

while x < 5:

print("test")

x = x + 1

print("will this print?")

22 of 47

Strings

23 of 47

Objectives: String Functions

Get string length

Index into a string to access individual characters

Get substring: part of a string

24 of 47

length

25 of 47

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' ',' '&' ' ' '?'

26 of 47

What is the length of each string?

'Fisk'

':)'

'Good morning!'

'$10.99'

'2 + 2 = 5'

4

2

13

6

9

27 of 47

len() function

len(s): returns number of characters in given string

len('Fisk')

len(':)')

len(' ')

len('Good morning!')

28 of 47

indexing

29 of 47

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

30 of 47

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

31 of 47

Indexing: Python Syntax

In Python, use square brackets [ ] to access character at an index

phrase = 'Welcome to Fisk University!'

phrase[0]

phrase[5]

32 of 47

Indexing Strings Practice

username = 'kittens27'

print(username[4])

print(username[7])

e

2

33 of 47

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])

34 of 47

slicing

35 of 47

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

36 of 47

Slicing Practice

name = 'Ariana Grande'

print(name[1:5])

print(name[:8])

print(name[2:])

‘rian’

‘Ariana G’

‘iana Grande’

37 of 47

Bonus string things

38 of 47

Concatenation

Sticking two parts together

Combine strings using + operator

name = "Jake"

intro = "My name is " + name

print(intro + " and I like snacks")

39 of 47

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)

40 of 47

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)

41 of 47

Other String Functions

Pre-written functions provided by Python, like len(s)!

docs.python.org/3/library/stdtypes.html#string-methods

42 of 47

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”

43 of 47

quote = ""Let's get internships" - students"

quote = '"Let's get internships" - students'

44 of 47

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)

45 of 47

Escaping

\n - newline

\t - tab

\" - quotation mark

\' - apostrophe

\\ - backslash

46 of 47

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

47 of 47

Questions?