SlideShare a Scribd company logo
Strings
Lecture 5
Announcements For This Lecture
Assignment 1
• Will post it on Sunday
§ Need one more lecture
§ But start reading it
• Due Wed Sep. 22nd
§ Revise until correct
§ Final version Sep 29th
• Do not put off until end!
Getting Help
• Can work in pairs
§ Will set up
§ Submit one for both
• Lots of consultant hours
§ Come early! Beat the rush
§ Also use TA office hours
• One-on-Ones next week
2
9/6/22 Strings
One-on-One Sessions
• Starting Monday: 1/2-hour one-on-one sessions
§ Bring computer to work with instructor, TA or consultant
§ Hands on, dedicated help with Labs 5 & 6 (and related)
§ To prepare for assignment, not for help on assignment
• Limited availability: we cannot get to everyone
§ Students with experience or confidence should hold back
• Sign up online in CMS: first come, first served
§ Choose assignment One-on-One
§ Pick a time that works for you; will add slots as possible
§ Can sign up starting at 5pm TOMORROW
9/6/22 Strings 3
One-on-One Sessions
• Starting Monday: 1/2-hour one-on-one sessions
§ Bring computer to work with instructor, TA or consultant
§ Hands on, dedicated help with Labs 5 & 6 (and related)
§ To prepare for assignment, not for help on assignment
• Limited availability: we cannot get to everyone
§ Students with experience or confidence should hold back
• Sign up online in CMS: first come, first served
§ Choose assignment One-on-One
§ Pick a time that works for you; will add slots as possible
§ Can sign up starting at 5pm TOMORROW
9/6/22 Strings 4
I personally have only 90 slots!
Leave those for students in need.
Even More Announcements
The AI Quiz
• Must finish before A1
§ Will reject assignment
§ Means a 0 by Sep 29th
• Current statistics
§ 50 have not passed
§ 15 have not taken
• E-mails sent tomorrow
Watching Videos?
• Today
§ Lesson 6: Strings
• Next Time
§ Lesson 7: Specifications
§ Lesson 8: Testing
§ Notice that it is a lot
§ Important for A1
9/6/22 Strings 5
Purpose of Today’s Lecture
• Return to the string (str) type
§ Saw it the first day of class
§ Learn all of the things we can do with it
• See more examples of functions
§ Particularly functions with strings
• Learn the difference between…
§ Procedures and fruitful functions
§ print and return statements
9/6/22 Strings 6
String: Text as a Value
• String are quoted characters
§ 'abc d' (Python prefers)
§ "abc d" (most languages)
• How to write quotes in quotes?
§ Delineate with “other quote”
§ Example: "Don't" or '6" tall'
§ What if need both " and ' ?
• Solution: escape characters
§ Format:  + letter
§ Special or invisible chars
9/6/22 Strings 7
Char Meaning
' single quote
" double quote
n new line
t tab
 backslash
>>> x = 'I said: "Don't"'
>>> print(x)
I said: "Don't"
String are Indexed
• s = 'abc d'
• Access characters with []
§ s[0] is 'a'
§ s[4] is 'd'
§ s[5] causes an error
§ s[0:2] is 'ab' (excludes c)
§ s[2:] is 'c d'
• Called “string slicing”
• s = 'Hello all'
• What is s[3:6]?
9/6/22 Strings 8
a b c d
0 1 2 3 4
H e l l o
0 1 2 3 4 5
a
6
l
7
l
8
A: 'lo a'
B: 'lo'
C: 'lo '
D: 'o '
E: I do not know
String are Indexed
• s = 'abc d'
• Access characters with []
§ s[0] is 'a'
§ s[4] is 'd'
§ s[5] causes an error
§ s[0:2] is 'ab' (excludes c)
§ s[2:] is 'c d'
• Called “string slicing”
• s = 'Hello all'
• What is s[3:6]?
9/6/22 Strings 9
a b c d
0 1 2 3 4
H e l l o
0 1 2 3 4 5
a
6
l
7
l
8
A: 'lo a'
B: 'lo'
C: 'lo '
D: 'o '
E: I do not know
CORRECT
String are Indexed
• s = 'abc d'
• Access characters with []
§ s[0] is 'a'
§ s[4] is 'd'
§ s[5] causes an error
§ s[0:2] is 'ab' (excludes c)
§ s[2:] is 'c d'
• Called “string slicing”
• s = 'Hello all'
• What is s[:4]?
9/6/22 Strings 10
a b c d
0 1 2 3 4
H e l l o
0 1 2 3 4 5
a
6
l
7
l
8
A: 'o all'
B: 'Hello'
C: 'Hell'
D: Error!
E: I do not know
String are Indexed
• s = 'abc d'
• Access characters with []
§ s[0] is 'a'
§ s[4] is 'd'
§ s[5] causes an error
§ s[0:2] is 'ab' (excludes c)
§ s[2:] is 'c d'
• Called “string slicing”
• s = 'Hello all'
• What is s[:4]?
9/6/22 Strings 11
a b c d
0 1 2 3 4
H e l l o
0 1 2 3 4 5
a
6
l
7
l
8
A: 'o all'
B: 'Hello'
C: 'Hell'
D: Error!
E: I do not know
CORRECT
Other Things We Can Do With Strings
• Operation in: s1 in s2
§ Tests if s1 “a part of” s2
§ Say s1 a substring of s2
§ Evaluates to a bool
• Examples:
§ s = 'abracadabra'
§ 'a' in s == True
§ 'cad' in s == True
§ 'foo' in s == False
• Function len: len(s)
§ Value is # of chars in s
§ Evaluates to an int
• Examples:
§ s = 'abracadabra’
§ len(s) == 11
§ len(s[1:5]) == 4
§ s[1:len(s)-1] == 'bracadabr'
9/6/22 Strings 12
Defining a String Function
• Start w/ string variable
§ Holds string to work on
§ Make it the parameter
• Body is all assignments
§ Make variables as needed
§ But last line is a return
• Try to work in reverse
§ Start with the return
§ Figure ops you need
§ Make a variable if unsure
§ Assign on previous line
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
# Start of middle third
# End of middle third
# Get the text
# Return the result
return result
9/6/22 Strings 13
Defining a String Function
• Start w/ string variable
§ Holds string to work on
§ Make it the parameter
• Body is all assignments
§ Make variables as needed
§ But last line is a return
• Try to work in reverse
§ Start with the return
§ Figure ops you need
§ Make a variable if unsure
§ Assign on previous line
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
# Start of middle third
# End of middle third
# Get the text
result = text[start:end]
# Return the result
return result
9/6/22 Strings 14
Defining a String Function
• Start w/ string variable
§ Holds string to work on
§ Make it the parameter
• Body is all assignments
§ Make variables as needed
§ But last line is a return
• Try to work in reverse
§ Start with the return
§ Figure ops you need
§ Make a variable if unsure
§ Assign on previous line
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
# Start of middle third
# End of middle third
end = 2*size//3
# Get the text
result = text[start:end]
# Return the result
return result
9/6/22 Strings 15
Defining a String Function
• Start w/ string variable
§ Holds string to work on
§ Make it the parameter
• Body is all assignments
§ Make variables as needed
§ But last line is a return
• Try to work in reverse
§ Start with the return
§ Figure ops you need
§ Make a variable if unsure
§ Assign on previous line
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
# Start of middle third
start = size//3
# End of middle third
end = 2*size//3
# Get the text
result = text[start:end]
# Return the result
return result
9/6/22 Strings 16
Defining a String Function
• Start w/ string variable
§ Holds string to work on
§ Make it the parameter
• Body is all assignments
§ Make variables as needed
§ But last line is a return
• Try to work in reverse
§ Start with the return
§ Figure ops you need
§ Make a variable if unsure
§ Assign on previous line
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
size = len(text)
# Start of middle third
start = size//3
# End of middle third
end = 2*size//3
# Get the text
result = text[start:end]
# Return the result
return result
9/6/22 Strings 17
Defining a String Function
>>> middle('abc')
'b'
>>> middle('aabbcc')
'bb'
>>> middle('aaabbbccc')
'bbb'
def middle(text):
"""Returns: middle 3rd of text
Param text: a string"""
# Get length of text
size = len(text)
# Start of middle third
start = size//3
# End of middle third
end = 2*size//3
# Get the text
result = text[start:end]
# Return the result
return result
9/6/22 Strings 18
Not All Functions Need a Return
def greet(n):
"""Prints a greeting to the name n
Parameter n: name to greet
Precondition: n is a string"""
print('Hello '+n+'!')
print('How are you?')
9/6/22 Strings 19
Displays these
strings on the screen
No assignments or return
The call frame is EMPTY
Note the difference
Procedures vs. Fruitful Functions
Procedures
• Functions that do something
• Call them as a statement
• Example: greet('Walker')
Fruitful Functions
• Functions that give a value
• Call them in an expression
• Example: x = round(2.56,1)
9/6/22 Strings 20
Historical Aside
• Historically “function” = “fruitful function”
• But now we use “function” to refer to both
Print vs. Return
Print
• Displays a value on screen
§ Used primarily for testing
§ Not useful for calculations
def print_plus(n):
print(n+1)
>>> x = print_plus(2)
3
>>>
Return
• Defines a function’s value
§ Important for calculations
§ But does not display anything
def return_plus(n):
return (n+1)
>>> x = return_plus(2)
>>>
9/6/22 Strings 21
Print vs. Return
Print
• Displays a value on screen
§ Used primarily for testing
§ Not useful for calculations
def print_plus(n):
print(n+1)
>>> x = print_plus(2)
3
>>>
Return
• Defines a function’s value
§ Important for calculations
§ But does not display anything
def return_plus(n):
return (n+1)
>>> x = return_plus(2)
>>>
9/6/22 Strings 22
x 3
x
Nothing here!
Method Calls
• Methods calls are unique (right now) to strings
§ Like a function call with a “string in front”
• Method calls have the form
string.name(x,y,…)
• The string in front is an additional argument
§ Just one that is not inside of the parentheses
§ Why? Will answer this later in course.
method
name
arguments
argument
9/6/22 Strings 23
Example: upper()
• upper(): Return an upper case copy
>>> s = 'Hello World’
>>> s.upper()
'HELLO WORLD'
>>> s[1:5].upper() # Str before need not be a variable
'ELLO'
>>> 'abc'.upper() # Str before could be a literal
'ABC’
• Notice that only argument is string in front
9/6/22 Strings 24
Examples of String Methods
• s1.index(s2)
§ Returns position of the
first instance of s2 in s1
• s1.count(s2)
§ Returns number of times
s2 appears inside of s1
• s.strip()
§ Returns copy of s with no
white-space at ends
>>> s = 'abracadabra'
>>> s.index('a')
0
>>> s.index('rac')
2
>>> s.count('a')
5
>>> s.count('x')
0
>>> ' a b '.strip()
'a b'
9/6/22 Strings 25
Examples of String Methods
• s1.index(s2)
§ Returns position of the
first instance of s2 in s1
• s1.count(s2)
§ Returns number of times
s2 appears inside of s1
• s.strip()
§ Returns copy of s with no
white-space at ends
>>> s = 'abracadabra'
>>> s.index('a')
0
>>> s.index('rac')
2
>>> s.count('a')
5
>>> s.count('x')
0
>>> ' a b '.strip()
'a b'
9/6/22 Strings 26
See Lecture page for more
Working on Assignment 1
• You will be writing a lot of string functions
• You have three main tools at your disposal
§ Searching: The index method
§ Cutting: The slice operation [start:end]
§ Gluing: The + operator
• Can combine these in different ways
§ Cutting to pull out parts of a string
§ Gluing to put back together in new string
9/6/22 Strings 27
String Extraction Example
def firstparens(text):
"""Returns: substring in ()
Uses the first set of parens
Param text: a string with ()"""
# SEARCH for open parens
start = text.index('(')
# CUT before paren
tail = text[start+1:]
# SEARCH for close parens
end = tail.index(')')
# CUT and return the result
return tail[:end]
>>> s = 'Prof (Walker) White'
>>> firstparens(s)
'Walker'
>>> t = '(A) B (C) D'
>>> firstparens(t)
'A'
9/6/22 Strings 28
String Extraction Puzzle
def second(text):
"""Returns: second elt in text
The text is a sequence of words
separated by commas, spaces.
Ex: second('A, B, C’) rets 'B'
Param text: a list of words"""
start = text.index(',') # SEARCH
tail = text[start+1:] # CUT
end = tail.index(',') # SEARCH
result = tail[:end] # CUT
return result
>>> second('cat, dog, mouse, lion')
'dog'
>>> second('apple, pear, banana')
'pear'
9/6/22 Strings 29
1
2
3
4
5
String Extraction Puzzle
def second(text):
"""Returns: second elt in text
The text is a sequence of words
separated by commas, spaces.
Ex: second('A, B, C’) rets 'B'
Param text: a list of words"""
start = text.index(',') # SEARCH
tail = text[start+1:] # CUT
end = tail.index(',') # SEARCH
result = tail[:end] # CUT
return result
>>> second('cat, dog, mouse, lion')
'dog'
>>> second('apple, pear, banana')
'pear'
9/6/22 Strings 30
1
2
3
4
5
Where is the error?
A: Line 1
B: Line 2
C: Line 3
D: Line 4
E: There is no error
String Extraction Puzzle
def second(text):
"""Returns: second elt in text
The text is a sequence of words
separated by commas, spaces.
Ex: second('A, B, C’) rets 'B'
Param text: a list of words"""
start = text.index(',') # SEARCH
tail = text[start+1:] # CUT
end = tail.index(',') # SEARCH
result = tail[:end] # CUT
return result
>>> second('cat, dog, mouse, lion')
'dog'
>>> second('apple, pear, banana')
'pear'
9/6/22 Strings 31
1
2
3
4
5
result = tail[:end].strip()
tail = text[start+2:]
OR

More Related Content

Similar to Python Lecture Slides topic strings handling (20)

‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings |
FabMinds
 
trisha comp ppt.pptx
trisha comp ppt.pptx
Tapaswini14
 
Python data handling
Python data handling
Prof. Dr. K. Adisesha
 
"Strings in Python - Presentation Slide"
"Strings in Python - Presentation Slide"
altacc1921
 
Strings in Python
Strings in Python
nitamhaske
 
Python Strings and its Featues Explained in Detail .pptx
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
varthini python .pptx
varthini python .pptx
MJeyavarthini
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
Python ds
Python ds
Sharath Ankrajegowda
 
Chapter05.ppt
Chapter05.ppt
afsheenfaiq2
 
Strings_Unit 3 .ppt
Strings_Unit 3 .ppt
hrithikexams
 
Chapter05
Chapter05
Wala Youssef Ghayada
 
BCSE101E_Python_Module5 (4).pdf
BCSE101E_Python_Module5 (4).pdf
mukeshb0905
 
Python String Revisited.pptx
Python String Revisited.pptx
Chandrapriya Jayabal
 
Python- strings
Python- strings
Krishna Nanda
 
Python Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
string manipulation in python ppt for grade 11 cbse
string manipulation in python ppt for grade 11 cbse
KrithikaTM
 
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
jaychoudhary37
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings |
FabMinds
 
trisha comp ppt.pptx
trisha comp ppt.pptx
Tapaswini14
 
"Strings in Python - Presentation Slide"
"Strings in Python - Presentation Slide"
altacc1921
 
Strings in Python
Strings in Python
nitamhaske
 
Python Strings and its Featues Explained in Detail .pptx
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
varthini python .pptx
varthini python .pptx
MJeyavarthini
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
Strings_Unit 3 .ppt
Strings_Unit 3 .ppt
hrithikexams
 
BCSE101E_Python_Module5 (4).pdf
BCSE101E_Python_Module5 (4).pdf
mukeshb0905
 
Python Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
string manipulation in python ppt for grade 11 cbse
string manipulation in python ppt for grade 11 cbse
KrithikaTM
 
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
jaychoudhary37
 

More from MuhammadIfitikhar (10)

Lecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
Lecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
Python course slides topic objects in python
Python course slides topic objects in python
MuhammadIfitikhar
 
Python Lecture slides topic Algorithm design
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
 
Python Slides conditioanls and control flow
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
Python course lecture slides specifications and testing
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
Python Course Lecture Defining Functions
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
Python Course Functions and Modules Slides
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
Python Lecture Slides Variables and Assignments
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
Course Overview Python Basics Course Slides
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Lecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
Lecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
Python course slides topic objects in python
Python course slides topic objects in python
MuhammadIfitikhar
 
Python Lecture slides topic Algorithm design
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
 
Python Slides conditioanls and control flow
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
Python course lecture slides specifications and testing
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
Python Course Lecture Defining Functions
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
Python Course Functions and Modules Slides
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
Python Lecture Slides Variables and Assignments
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
Course Overview Python Basics Course Slides
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Ad

Recently uploaded (20)

Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Making significant Software Architecture decisions
Making significant Software Architecture decisions
Bert Jan Schrijver
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Making significant Software Architecture decisions
Making significant Software Architecture decisions
Bert Jan Schrijver
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Software Testing & it’s types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Ad

Python Lecture Slides topic strings handling

  • 2. Announcements For This Lecture Assignment 1 • Will post it on Sunday § Need one more lecture § But start reading it • Due Wed Sep. 22nd § Revise until correct § Final version Sep 29th • Do not put off until end! Getting Help • Can work in pairs § Will set up § Submit one for both • Lots of consultant hours § Come early! Beat the rush § Also use TA office hours • One-on-Ones next week 2 9/6/22 Strings
  • 3. One-on-One Sessions • Starting Monday: 1/2-hour one-on-one sessions § Bring computer to work with instructor, TA or consultant § Hands on, dedicated help with Labs 5 & 6 (and related) § To prepare for assignment, not for help on assignment • Limited availability: we cannot get to everyone § Students with experience or confidence should hold back • Sign up online in CMS: first come, first served § Choose assignment One-on-One § Pick a time that works for you; will add slots as possible § Can sign up starting at 5pm TOMORROW 9/6/22 Strings 3
  • 4. One-on-One Sessions • Starting Monday: 1/2-hour one-on-one sessions § Bring computer to work with instructor, TA or consultant § Hands on, dedicated help with Labs 5 & 6 (and related) § To prepare for assignment, not for help on assignment • Limited availability: we cannot get to everyone § Students with experience or confidence should hold back • Sign up online in CMS: first come, first served § Choose assignment One-on-One § Pick a time that works for you; will add slots as possible § Can sign up starting at 5pm TOMORROW 9/6/22 Strings 4 I personally have only 90 slots! Leave those for students in need.
  • 5. Even More Announcements The AI Quiz • Must finish before A1 § Will reject assignment § Means a 0 by Sep 29th • Current statistics § 50 have not passed § 15 have not taken • E-mails sent tomorrow Watching Videos? • Today § Lesson 6: Strings • Next Time § Lesson 7: Specifications § Lesson 8: Testing § Notice that it is a lot § Important for A1 9/6/22 Strings 5
  • 6. Purpose of Today’s Lecture • Return to the string (str) type § Saw it the first day of class § Learn all of the things we can do with it • See more examples of functions § Particularly functions with strings • Learn the difference between… § Procedures and fruitful functions § print and return statements 9/6/22 Strings 6
  • 7. String: Text as a Value • String are quoted characters § 'abc d' (Python prefers) § "abc d" (most languages) • How to write quotes in quotes? § Delineate with “other quote” § Example: "Don't" or '6" tall' § What if need both " and ' ? • Solution: escape characters § Format: + letter § Special or invisible chars 9/6/22 Strings 7 Char Meaning ' single quote " double quote n new line t tab backslash >>> x = 'I said: "Don't"' >>> print(x) I said: "Don't"
  • 8. String are Indexed • s = 'abc d' • Access characters with [] § s[0] is 'a' § s[4] is 'd' § s[5] causes an error § s[0:2] is 'ab' (excludes c) § s[2:] is 'c d' • Called “string slicing” • s = 'Hello all' • What is s[3:6]? 9/6/22 Strings 8 a b c d 0 1 2 3 4 H e l l o 0 1 2 3 4 5 a 6 l 7 l 8 A: 'lo a' B: 'lo' C: 'lo ' D: 'o ' E: I do not know
  • 9. String are Indexed • s = 'abc d' • Access characters with [] § s[0] is 'a' § s[4] is 'd' § s[5] causes an error § s[0:2] is 'ab' (excludes c) § s[2:] is 'c d' • Called “string slicing” • s = 'Hello all' • What is s[3:6]? 9/6/22 Strings 9 a b c d 0 1 2 3 4 H e l l o 0 1 2 3 4 5 a 6 l 7 l 8 A: 'lo a' B: 'lo' C: 'lo ' D: 'o ' E: I do not know CORRECT
  • 10. String are Indexed • s = 'abc d' • Access characters with [] § s[0] is 'a' § s[4] is 'd' § s[5] causes an error § s[0:2] is 'ab' (excludes c) § s[2:] is 'c d' • Called “string slicing” • s = 'Hello all' • What is s[:4]? 9/6/22 Strings 10 a b c d 0 1 2 3 4 H e l l o 0 1 2 3 4 5 a 6 l 7 l 8 A: 'o all' B: 'Hello' C: 'Hell' D: Error! E: I do not know
  • 11. String are Indexed • s = 'abc d' • Access characters with [] § s[0] is 'a' § s[4] is 'd' § s[5] causes an error § s[0:2] is 'ab' (excludes c) § s[2:] is 'c d' • Called “string slicing” • s = 'Hello all' • What is s[:4]? 9/6/22 Strings 11 a b c d 0 1 2 3 4 H e l l o 0 1 2 3 4 5 a 6 l 7 l 8 A: 'o all' B: 'Hello' C: 'Hell' D: Error! E: I do not know CORRECT
  • 12. Other Things We Can Do With Strings • Operation in: s1 in s2 § Tests if s1 “a part of” s2 § Say s1 a substring of s2 § Evaluates to a bool • Examples: § s = 'abracadabra' § 'a' in s == True § 'cad' in s == True § 'foo' in s == False • Function len: len(s) § Value is # of chars in s § Evaluates to an int • Examples: § s = 'abracadabra’ § len(s) == 11 § len(s[1:5]) == 4 § s[1:len(s)-1] == 'bracadabr' 9/6/22 Strings 12
  • 13. Defining a String Function • Start w/ string variable § Holds string to work on § Make it the parameter • Body is all assignments § Make variables as needed § But last line is a return • Try to work in reverse § Start with the return § Figure ops you need § Make a variable if unsure § Assign on previous line def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third # Get the text # Return the result return result 9/6/22 Strings 13
  • 14. Defining a String Function • Start w/ string variable § Holds string to work on § Make it the parameter • Body is all assignments § Make variables as needed § But last line is a return • Try to work in reverse § Start with the return § Figure ops you need § Make a variable if unsure § Assign on previous line def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third # Get the text result = text[start:end] # Return the result return result 9/6/22 Strings 14
  • 15. Defining a String Function • Start w/ string variable § Holds string to work on § Make it the parameter • Body is all assignments § Make variables as needed § But last line is a return • Try to work in reverse § Start with the return § Figure ops you need § Make a variable if unsure § Assign on previous line def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third end = 2*size//3 # Get the text result = text[start:end] # Return the result return result 9/6/22 Strings 15
  • 16. Defining a String Function • Start w/ string variable § Holds string to work on § Make it the parameter • Body is all assignments § Make variables as needed § But last line is a return • Try to work in reverse § Start with the return § Figure ops you need § Make a variable if unsure § Assign on previous line def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text # Start of middle third start = size//3 # End of middle third end = 2*size//3 # Get the text result = text[start:end] # Return the result return result 9/6/22 Strings 16
  • 17. Defining a String Function • Start w/ string variable § Holds string to work on § Make it the parameter • Body is all assignments § Make variables as needed § But last line is a return • Try to work in reverse § Start with the return § Figure ops you need § Make a variable if unsure § Assign on previous line def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text size = len(text) # Start of middle third start = size//3 # End of middle third end = 2*size//3 # Get the text result = text[start:end] # Return the result return result 9/6/22 Strings 17
  • 18. Defining a String Function >>> middle('abc') 'b' >>> middle('aabbcc') 'bb' >>> middle('aaabbbccc') 'bbb' def middle(text): """Returns: middle 3rd of text Param text: a string""" # Get length of text size = len(text) # Start of middle third start = size//3 # End of middle third end = 2*size//3 # Get the text result = text[start:end] # Return the result return result 9/6/22 Strings 18
  • 19. Not All Functions Need a Return def greet(n): """Prints a greeting to the name n Parameter n: name to greet Precondition: n is a string""" print('Hello '+n+'!') print('How are you?') 9/6/22 Strings 19 Displays these strings on the screen No assignments or return The call frame is EMPTY Note the difference
  • 20. Procedures vs. Fruitful Functions Procedures • Functions that do something • Call them as a statement • Example: greet('Walker') Fruitful Functions • Functions that give a value • Call them in an expression • Example: x = round(2.56,1) 9/6/22 Strings 20 Historical Aside • Historically “function” = “fruitful function” • But now we use “function” to refer to both
  • 21. Print vs. Return Print • Displays a value on screen § Used primarily for testing § Not useful for calculations def print_plus(n): print(n+1) >>> x = print_plus(2) 3 >>> Return • Defines a function’s value § Important for calculations § But does not display anything def return_plus(n): return (n+1) >>> x = return_plus(2) >>> 9/6/22 Strings 21
  • 22. Print vs. Return Print • Displays a value on screen § Used primarily for testing § Not useful for calculations def print_plus(n): print(n+1) >>> x = print_plus(2) 3 >>> Return • Defines a function’s value § Important for calculations § But does not display anything def return_plus(n): return (n+1) >>> x = return_plus(2) >>> 9/6/22 Strings 22 x 3 x Nothing here!
  • 23. Method Calls • Methods calls are unique (right now) to strings § Like a function call with a “string in front” • Method calls have the form string.name(x,y,…) • The string in front is an additional argument § Just one that is not inside of the parentheses § Why? Will answer this later in course. method name arguments argument 9/6/22 Strings 23
  • 24. Example: upper() • upper(): Return an upper case copy >>> s = 'Hello World’ >>> s.upper() 'HELLO WORLD' >>> s[1:5].upper() # Str before need not be a variable 'ELLO' >>> 'abc'.upper() # Str before could be a literal 'ABC’ • Notice that only argument is string in front 9/6/22 Strings 24
  • 25. Examples of String Methods • s1.index(s2) § Returns position of the first instance of s2 in s1 • s1.count(s2) § Returns number of times s2 appears inside of s1 • s.strip() § Returns copy of s with no white-space at ends >>> s = 'abracadabra' >>> s.index('a') 0 >>> s.index('rac') 2 >>> s.count('a') 5 >>> s.count('x') 0 >>> ' a b '.strip() 'a b' 9/6/22 Strings 25
  • 26. Examples of String Methods • s1.index(s2) § Returns position of the first instance of s2 in s1 • s1.count(s2) § Returns number of times s2 appears inside of s1 • s.strip() § Returns copy of s with no white-space at ends >>> s = 'abracadabra' >>> s.index('a') 0 >>> s.index('rac') 2 >>> s.count('a') 5 >>> s.count('x') 0 >>> ' a b '.strip() 'a b' 9/6/22 Strings 26 See Lecture page for more
  • 27. Working on Assignment 1 • You will be writing a lot of string functions • You have three main tools at your disposal § Searching: The index method § Cutting: The slice operation [start:end] § Gluing: The + operator • Can combine these in different ways § Cutting to pull out parts of a string § Gluing to put back together in new string 9/6/22 Strings 27
  • 28. String Extraction Example def firstparens(text): """Returns: substring in () Uses the first set of parens Param text: a string with ()""" # SEARCH for open parens start = text.index('(') # CUT before paren tail = text[start+1:] # SEARCH for close parens end = tail.index(')') # CUT and return the result return tail[:end] >>> s = 'Prof (Walker) White' >>> firstparens(s) 'Walker' >>> t = '(A) B (C) D' >>> firstparens(t) 'A' 9/6/22 Strings 28
  • 29. String Extraction Puzzle def second(text): """Returns: second elt in text The text is a sequence of words separated by commas, spaces. Ex: second('A, B, C’) rets 'B' Param text: a list of words""" start = text.index(',') # SEARCH tail = text[start+1:] # CUT end = tail.index(',') # SEARCH result = tail[:end] # CUT return result >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' 9/6/22 Strings 29 1 2 3 4 5
  • 30. String Extraction Puzzle def second(text): """Returns: second elt in text The text is a sequence of words separated by commas, spaces. Ex: second('A, B, C’) rets 'B' Param text: a list of words""" start = text.index(',') # SEARCH tail = text[start+1:] # CUT end = tail.index(',') # SEARCH result = tail[:end] # CUT return result >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' 9/6/22 Strings 30 1 2 3 4 5 Where is the error? A: Line 1 B: Line 2 C: Line 3 D: Line 4 E: There is no error
  • 31. String Extraction Puzzle def second(text): """Returns: second elt in text The text is a sequence of words separated by commas, spaces. Ex: second('A, B, C’) rets 'B' Param text: a list of words""" start = text.index(',') # SEARCH tail = text[start+1:] # CUT end = tail.index(',') # SEARCH result = tail[:end] # CUT return result >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' 9/6/22 Strings 31 1 2 3 4 5 result = tail[:end].strip() tail = text[start+2:] OR