Download Manipulating strings, String methods, dot notation

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
2
CompSci101-PrinciplesofProgramming
Learningoutcomes
! Attheendofthislecture,studentsshouldbeableto:
!  usedotnota0on(usingstringmethodswithstringinstances)
!  usestringmethods:upper(),lower(),strip(),find(),rfind()
!  usetheinbuiltfunc0ons:min(),max(),round(),abs()
COMPSCI11
PrinciplesofProgramming
Lecture5–Manipula0ngstrings,String
methods,dotnota0on
3
CompSci101-PrinciplesofProgramming
Recap
! Fromlecture4
! 
! 
! 
! 
Usethelen()func0ontocalculatehowmanycharactersareinastring
Obtainasinglecharacterfromastring
Slicestrings
words = " Prince Charming "!
Concatenatestrings
length = len(words)!
!
letter1 = words[3]!
inc Princ e Charming
ng
im g!
letter2 = words[-5]!
letter3 = words[len(words) - 2]!
!
letters1 = words[3:6]!
letters2 = words[:6]!
letters3 = words[6:]!
letters4 = words[-3:]!
!
word = letter1 + letter2!
4
CompSci101-PrinciplesofProgramming
Dotnota0on
! Everyobjecttype,aswellasstoringsomedata,hassomedefined
methodswhichcanbeappliedtothatpar0culartypeofobject.
! Variableswhichreferenceanobjectarecalledinstances,e.g.,inthe
followingcode,gree0ngisastringinstanceandnumberisan
instanceoftypeint.
greeting = "Hello World"!
number = 234!
! Stringinstanceshavemanymethodswhichcanbeappliedtothem
suchasupper(),lower(),find(),strip(),isalpha(),isdigit(),rfind(),
split()….Inthislecturewewilllookatafewofthesemethods.
! Inordertoapplyamethodtoanobjectweusedotnota7on,i.e.,the
variablename,followedbyadot,followedbythemethodname.
word = word + " " + letter3!
!
instance_name.method_name(…)
print(letters1, letters2, letters3, letters4, word)!
Notethat,methods(likefunc7ons)useparentheses(roundbrackets)
aEerthemethodname.
5
CompSci101-PrinciplesofProgramming
6
CompSci101-PrinciplesofProgramming
Stringmethods–upper(),lower()
Stringmethods–find()
! Thefind()methodisusedtolookfortheposi0on(indexnumber)of
thefirstoccurrence(fromtheleY)ofsomecharacters.Ifthe
charactersarefound,thefind()methodreturnstheindexnumber,
otherwisethefind()methodreturns-1.
! Theupper()methodreturnsanewstringobjectwithallthe
charactersconvertedtouppercase.Thelower()methodreturnsa
newstringobjectwithallthecharactersconvertedtolowercase.
! Forexample,
010100101 !
greeting!
010100101 !
H! e! l! l! o!
greeting = "Hello World"!
0!
greeting_lower = greeting.lower()!
greeting_upper = greeting.upper()!
1!
2!
3!
W! o! r! l! d!
4!
5!
6!
7!
8!
9!
10!
Forexample,
!
greeting = "Hello World"!
print(greeting, greeting_lower, greeting_upper)!
position1 = greeting.find(" ")!
position2 = greeting.find("z")!
position3 = greeting.find("orl")!
Hello World hello world HELLO WORLD!
print(position1, position2, position3)!
No7cethatthereisatotalofthreestringobjects
7
CompSci101-PrinciplesofProgramming
CompSci101-PrinciplesofProgramming
Stringmethods–rfind()
! Therfind()methodisusedtolookfortheindexposi0onofthelast
occurrence(fromtheright)ofsomecharacters.Ifthecharacters
arefound,therfind()methodreturnstheindexnumber,otherwise
therfind()methodreturns-1.
010100101 !
greeting!
010100101 !
H! e! l! l! o!
0!
1!
2!
3!
4!
W! o! r! l! d!
5!
6!
7!
8!
9!
greeting = "Hello World"!
! Thestrip()methodreturnsanewstringobjectwithallwhitespace
fromthebeginningandendofthestringremoved.Itdoesnot
removespacesfrominsidethestring.
Forexample,
letters1 = "
H e l l o oooo
letters2
= letters1.strip()!
"!
print(length1, length2, letters1, letters2, sep = "***")!
477-1
position2 = greeting.rfind("o")!
21***14***
H e l l o oooo
***H e l l o oooo!
position3 = greeting.rfind("orl")!
position4 = greeting.rfind("lro")!
print(position1, position2, position3, position4)!
8
Stringmethods–strip()
length1 = len(letters1)!
length2 = len(letters2)!
! Forexample,
position1 = greeting.find("o")!
10!
5 -1 7!
No7cethattherearetwostringobjects
CompSci101-PrinciplesofProgramming
9
CompSci101-PrinciplesofProgramming
Exercise
! Completethefollowingprogramsothatitprintstheini0alfromthe
firstnamefollowedbyafullstop,aspaceandfollowedbythe
surname.Assumethefullnameisalwaystwonamesseparatedbya
singlespace.
10
CommonPythoninbuiltfunc0ons
! min()isaninbuiltfunc7onwhichcanbeusedtofindthesmallest
numberfromacommaseparatedsetofnumbersandmax()isthe
inbuiltfunc7onwhichcanbeusedtofindthelargestnumberfrom
acommaseparatedsetofnumbers,e.g.,
full_name = "Wystan Auden"!
!
num1 = 32!
num2 = 16!
!
!
smallest = min(num1, num2)!
print(smallest)!
!
!
!
!
smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2)!
!
initialled_name = first_letter + ". " + last_name!
!
print(initialled_name)!
print(largest)!
print(smallest)!
largest = max(num1, num2)!
largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2)!
W. Auden!
print(largest)!
FuneralBlues:Stopalltheclocks,cutoffthetelephone/Preventthedogfrombarking…
CompSci101-PrinciplesofProgramming
11
CompSci101-PrinciplesofProgramming
CommonPythoninbuiltfunc0ons
! Theinbuiltfunc7on,round(),isusedtoroundnumberstothe
closestwholenumber(orroundedtoanumberofdigitsaYerthe
decimalpoint),e.g.,
16!
-1.2!
32!
56.99!
CommonPythoninbuiltfunc0ons
! Notethatthefunc7on,round()withasingleargumentreturnsan
intnumberandthatroundinganintreturnstheintunchanged,e.g.,
num1 = 32.657123!
print("round(32.657123, 0): ", round(32.657123, 0))!
print("round(16.48926, 0): ", round(16.48926, 0))!
num2 = 16.48926!
print("round(32.657123): ", round(32.657123))!
num3 = -16.48926!
print("round(16.48926): ", round(16.48926))!
print("round(24.0, 0): ", round(24.0, 0))!
!
print(round(num1))!
print(round(num2))!
print(round(num3))!
print()!
!
print(round(num1, 2))!
print(round(num2, 3))!
print(round(num3, 4))!
print("round(24.0, 1): ", round(24.0, 1))!
print("round(24, 0): ", round(24, 0))!
33!
16!
-16!
!
32.66!
16.489!
-16.4893!
12
print("round(24.0): ", round(24.0))!
print("round(24): ", round(24))!
!
round(32.657123,0):33.0
round(16.48926,0):16.0
round(32.657123):33
round(16.48926):16
round(24.0,0):24.0
round(24.0,1):24.0
round(24,0):24
round(24.0):24
round(24):24!
CompSci101-PrinciplesofProgramming
13
CompSci101-PrinciplesofProgramming
CommonPythoninbuiltfunc0ons
! Theinbuiltfunc7on,abs(),isusedtogettheabsolutevalue(the
magnitude)ofanumber(intorfloat),e.g.,
round()–unexpectedresult
! Some0mestheround()func0onseemstogiveanunexpectedresult
e.g., num1 = 1.5!
num2 = 2.5
num1 = 32!
32!
32!
7!
16.78!
num2 = -32!
num3 = abs(16 - 23)!
!
print(abs(num1))!
14
!
num3 = 3.5!
print(round(num1))!
2!
print(round(num2)) #surprising result!
4!
2!
print(round(num3))!
! Thisproblemhappensbecausefloa0ngpointnumbersarestoredina
finitespace,e.g.,0.1hasaninfinitenumberofdigitswhenconverted
tobase2
0.00011001100110011001100110011001100110011001...!
but,whenstoredinthecomputermemory,floatnumbersareassigned
exactly64bitsofspacewhichmeansthatsomeofthebitsarecutoff.
Perhaps2.5isactuallystoredas2.49999999999999999…99
whichisroundedto2(nottheexpected3).
print(abs(num2))!
print(num3)!
print(abs(-16.78))!
round(4.235, 2) gives the number 4.24!
round(4.265, 2) gives the number 4.26!
CompSci101-PrinciplesofProgramming
15
CompSci101-PrinciplesofProgramming
Exercise
! Completethefollowingprogramsothatitprintsthetotaltaxandthe
netpayroundedtoawholenumber.Thefirst$14000isnottaxed.
Thenextamountupto$38500istaxedat24%andtherestistaxedat
34%.
Salary: $54000!
Amount to be taxed at: 24%: $24500!
Tax at rate1: $5880!
salary = 54000!
Amount to be taxed at: 34%: $15500!
Tax at rate2: $5270!
no_tax_boundary = 14000! ===============================!
rate1_boundary = 38500! Total tax: $11150!
!
rate1 = 0.24!
Net pay: $42850!
rate2 = 0.34!
===============================!
!
!
!
!
print("===============================")!
print("Total tax: $", total_tax, sep = "") !
print()!
print("Net pay: $", net_pay, sep = "") !
print("===============================")!
16
Summary
! InPython:
!  usedotnota0onwhenusingstringmethodswithstringinstances
!  thestringmethods:upper(),lower(),strip(),find(),rfind()canbeusedwithstring
instances
!  SomePythoninbuiltfunc0onsare:min(),max(),round()
CompSci101-PrinciplesofProgramming
17
ExamplesofPythonfeaturesusedinthislecture
!greeting = "Hello World"!
!position1 = greeting.find("o")!
!position2 = greeting.rfind("o")!
!position3 = words.find("Z")!
!position4 = words.rfind("o W")!
!!
!greeting_lower = greeting.lower()!
!greeting_upper = greeting.upper()!
!
!smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2)!
!largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2)!
!
!num1 = 32.657123!
!print(round(num1))!
!print(round(num1, 2))!
!
!num2 = abs(20 – num1)!
!print(num2)!
!
!!