Chapter 7 - Strings
Chapter 7 - Strings
Outline
• String as a sequence
• Indexing
• Mutability and Immutability
• Searching
• String Comparison
M o n t y P y t h o n
>>> print(s[0:2])
Mo
>>>print(s[:2]) #What will be printed?
>>>print(s[5:]) # What will be printed?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 9
Slicing cont’d
▪ You can use indexes to slice (extract a piece of) a string
▪ aStr[i:j] is the substring that begins with index i and ends with (but does not
include) index j H E L L O , W O R L D
>>> greeting = ‘HELLO, WORLD'
>>> greeting[1:3] 0 1 2 3 4 5 6 7 8 9 10 11
'EL'
>>> greeting[-3:-1] -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
'RL'
▪ omit begin or end to mean 'as far as you can go'
>>> print(greeting[:4], greeting[7:])
HELL WORLD
▪ aStr[i:j:k] is the same, but takes only every k-th character
>>> greeting[3:10:2]#steps by 2, picking every other character
'L,WR‘
Takeaway exercise: make it step by 3
anObject.methodName(parameterList)
▪ For example,
>>> 'avocado'.index('a')
0
• returns the index of the first 'a' in 'avocado'
▪ You can also use a variable of type string
• Takeaway question: Why is the “!” not removed in the above output?
• The string module contains a useful variable for this, called
punctuation (like how the math module has pi)
• So, how can we clean up every word in a sentence, once we've split it?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 27
split() and strip() together cont’d
▪ The strip() method works on one “word” at a time
▪ So, take it one word at a time
▪ How to replace only the second and the fifth occurrence of ‘saw’ with
‘SOW’, to output: I saw a SOW cutting a saw. I never saw such a SOW!
▪ (next slide)