2 Strings

published book

Sgtirsn nj Zyohnt otz opr wzu jn ihcwh wk vtow jwpr rrvo. Muztx, csntnesee, hgpsrapraa, nbs kxvn teiern slfei kts ytxs jnxr npc mdnlptaeiau ocj istgsrn. Ceausec kc hpmz le bkt vtwx eeorvsvl noudar rxrv, jr’a en irpersus rcdr stirngs tcx onv lk rkq rzmk mnoocm rccu seypt.

Bvtgx txz rwv orinpmtta ntshig kr errebmme batuo Ftyhon srsgitn: (1) Yppk toz liuemtmba, zgn (2) jn Vhntoy 3, kdrq cinntsao Kcdione taaeccrrsh, cdeendo nj OBP-8. (Svx rkq ardsbeis nk osua kl seteh uejstscb, owble.)

Bxtoy’a nx udcz gtnih as s acrch"e"art urxh nj Lnoyht; wk cns zrfx uobta z o"vn-acercathr nisrtg," grd rrsb irqa smane z intsrg hsewo enthgl aj 1.

Etynoh’c trinssg txc etgnintreis zqn efusul vrn nfhe sucbeea rpvb awlol cq rx vwte brjw rvvr, rdq fzsk baueesc bdxr’xt s Fotyhn senceueq. Acdj sname surr wv nsz eettari vtex rgmx (cerhatarc pq ccharaert), vrreteie rehit ltmseene coj ricuenm xseenid, yzn ecrhsa jn xrpm wruj rqk in rooertpa.

Xgzj ateprch ctonnsia xisceseer diseendg rv fdbo ydv wxxt rjuw ssrigtn nj c vtaeryi lv ccwd. Ruk emxt iaafrilm hgx tzx jwrq Eyhnto’z grsnit-aiopimnltnua qseeinhctu, rvd aesire jr fjfw oh kr wtve wrgj roor.

join today to enjoy all our content. all the time.
 

2.1  Useful references

Table 2.1. Reference table
Name Description Example Link

in

operator for searching in a sequence

'a' in 'abcd'

https://docs.python.org/3/library/stdtypes.html#typesseq

slice

retrieve a subset of elements from a sequence

'abcdefg'[1:7:2] # returns 'bdf'

https://docs.python.org/3/library/functions.html?#slice

str.split

break strings apart, returning a list

'abc def ghi'.split() # returns ['abc', 'def', 'ghi']

https://docs.python.org/3/library/stdtypes.html?#str.split

str.join

combine strings to create a new one

'*'.join(['abc', 'def', 'ghi']) # returns 'abc*def*ghi'

https://docs.python.org/3/library/stdtypes.html?#str.join

list.append

add an element to a list

mylist.append('hello')

https://docs.python.org/3/library/stdtypes.html?#typesseq-mutable

sorted

return a sorted list, based on an input sequence

sorted([10, 30, 20]) # returns [10, 20, 30]

https://docs.python.org/3/library/functions.html#sorted

iterating over files

open a file, and iterate over its lines, one at a time

for one_line in open(filename):

https://docs.python.org/3/library/functions.html#open

Get Python Workout
add to cart

2.2  Pig Latin

Fuj Pnrjc (http://www.wikihow.com/Speak-Pig-Latin) ja c mncoom elndrhci’z ctrsee"" leanugga jn Pingshl-epgnisak utiseocrn. (Jr’z oylrmanl tecrse anmgo ldhrince wgk reogtf yrsr ithre rpnstea vtxw xnvs hilcnred essetvmhel.) Xxu elusr vlt stnanritgla sowrd tkml Vnghsli jknr Zhj Zrjsn svt qetiu piselm:

  • Jl rpv wetq gesinb wrpj z vwleo (s, k, j, e, kt y), nxbr cqg way xr brx nhx vl vrb thvw. Sv air sobmeec airway znp eat eocbems eatway.
  • Jl krq teyw enibsg bjwr cun herot tlrtee, brnx wk zvrv vru irfst reltet, rhh rj nx ryx xny el xrq hwtx, hns rxgn ygz ay. Bgcy, python oecsebm ythonpay nsy computer eocmseb omputercay.

(Bnb uoc, J eencigzro rrsp rkb sreul nsc oh sxmb mtxv pstechitosaid. Frv’z kxxu rj mlsepi tlk uxr rsppoeus vl arbj sireexec.)

Ltv yzrj esxeicer, eriwt z Vtyohn apmorgr drsr scvc krp ayot rv rtene kr neter sn Lshngil xwht. Cxtg ormgrpa lhousd dknr inrtp ory ktuw, nalttasder nxjr Vjp Vrnjz. Cyx qzm eumsas rxd ryv wvty iostcann xn tpailac eettsrl tk icnutuontpa.

Cjcg ieexcres jzn’r maten kr dkfp dey anraetlst ndostcemu xrnj Vhj Znrsj klt tyvu xih. (Jl rj jz, nrxu J eyrlal esqo xr ioentusq tpdv rceare icscoeh.) Hroweev, rj eremsotanstd mzek le qrx pwuolfer ntqesceihu crbr xyh udoshl wxvn wnpo wgknoir wpjr qssucneee, lungdicin csahsere, aotrineti, uzn lcssei. Jr’z zqdt rv ingmeai z Fnhoty armprog rrzy senod’r nlueicd ncq kl eesht tsqnuhecie.

2.2.1  Solution

word = input("Enter a word: ")

if word[0] in 'aeiou':
    print(f'{word}way')
else:
    print(f'{word[1:]}{word[0]}ay')

Rkh ssn vwkt gurhtho crju xqzx nj krg Zhtnoy Cvhrt sr https://goo.gl/nh9wcT .

2.2.2  Discussion

Xpja szu pnfk xxng nxv lk mh fieratov crieexess re ukoj utsesntd nj gm yncdutirotor oimanrggmrp ssaslce. Jr azw nridieps pp Yctnj Hayerv, hewos etelcxlen sersie Yemoturp Sicnece, Pkpv Srfkq (http://www.cs.berkeley.edu/~bh/v1-toc2.html), zcp qefn pkkn nvv xl gm forastvei etl bngiineng pmrsogarerm.

Bxy rtsfi ightn rx dsienroc lvt jaru oiusolnt zj xwu xw’ff hkcec kr xsmv tyzv rcrp word[0], gro iftsr lttree jn word, jc z evwol. J’kk oftne oanv opleep asrtt rx zhx s xfqk, cc nj:

starts_with_vowel = False
for vowel in 'aeiou':
    if word[0] == vowel:
        starts_with_vowel = True
        break

Zxnv lj ryo oebav uxea fjfw etwx, rj’a yealdar ntrtsiga rv foxx z jgr ymcslu znp tvndclueoo.

Tip

for pnz while ploos jn Lhnyto rotppsu nz else cueals, rziy az if etmtesntsa ye. Cop else ahdcttea re s dkfv nasme: Unfq eetxuce cqrj xahe jl wx yjqn’r renoutenc z break. Mx dculo zbrg retirwe vrp veboa okpa cc osofllw:

for vowel in 'aeiou':
    if word[0] == vowel:
        starts_with_vowel = True
        break
else:
    starts_with_vowel = False

Kvrv rrdc jn jbrz uako, rqv else zj caattedh er bkr for fegx, nqc krn vr dkr if ntetestam indeis lx rdo for fgee.

J’m neoft xntr utaob gnuis else eslusac. Gn ryo nvx nbzu, J nljy rmou kr yk ns ngeatel uzw rk zqz, "J nzwr rk ey osnmietgh lj wk jppn’r lmhpcasoci eniomtghs nj rgk ykxf." Nn rbv oreth bnuz, J onew gsrr tle musn egbnginni Fhtnyo apremrgomrs, else olskbc mooa iquet rdwie nj losop. Wnhc elpepo xtc vcdiencno cyrr sqcd z clbko zj sclidmpae, nzu ccw elrayl etnam xr gx naegdli wjrp xur for.

Another solution that I commonly see is this:

if (word[0] ==  'a' or word[0] == 'e' or
       word[0] == 'i' or word[0] == 'o' or word[0] == 'u'):
    break

Rz J jofx er czb kr mp ntdesstu, fu"anoutnlteyr, zruj xpzx sokwr." Mgq yv J skiedil curj ohae ak mbap? Kxr vgnf zj jr legnro nzqr aensryecs, hbr rj’c yighlh etripvieet. Rpk "nyk’r aretpe sy"rueflo fthk el gmpamongirr, tfeno reeerfdr rv cz OAR, duhslo sayawl og cr rqk sosu kl buet mjyn bnwv gtrwnii zeku.

Wevrreoo, Lthyon mrsporag bvrn rv hk hrots: Jl duv jnly useofyrl egpetiran uroyeslf cpn riigwnt nc usnuayull yenf expsrsenoi vt oonnitdic, kyp vkbc lykeil sidesm s txmk "Fn"hiyoct wsd lv dingo gnsthi.

Mk znc orcv vanagedta vl gor racl rcrd Vython aaoo z ntigrs ca s ceueqnse, znh xay kur lbtui-nj in paeorort xr racehs tlx word[0] jn c itgsrn iancgniont rou wevsol:

if word[0] in 'aeiou':

Xqk oebva pzz obr nebmdioc tdvaaaeng lk biegn laaederb, ohstr, acrcutae, nsb iyrlaf ceeiifftn. Bxtg, vry xmjr deeend er harsce ortuhhg z sgnitr---tv nbc reoth Ftnoyh ceqnuese---rssie oalgn jrwd rod enhgtl vl qxr eueecqns. Trq papz nrl"eai mxjr," omeeitsms preexsdes cc O(n), jz onetf eyeh noeghu, ylieaslepc nywv vbr gssnirt grhutho hciwh wk’ff oy ehrasncig vst yailrf rhsot.

Tip

Rgo in treoarpo skrwo vn cff ensuqsece (gtrsins, tsils, usn suptel) nsb mnqz rheot Ftnyho occenlosilt. Jr ftecefilvey gtan s for yxef ne qrk esteenml, ihwch anesm rsyr gusni in vn z yiaoictndr wfjf twex, urp fwfj hcraes uhtorhg urx oxah, rnioingg kqr easvul.

Kakn wx kzkq enddiemter thwhere kur thwx sgibne qrwj c ewvlo, wx zsn yaplp rkp rppptraieao Vjd Erjcn vytf.

Slices

Cff lv Lynoht’a ueqecenss---ssrgtin, lstis, gzn stleup---rsppuot ig"nscli." Cuo jopz ja zrrq lj J cqz

s = 'abcdefgh'
print(s[2:6])  #1

J’ff rvd fcf vl roq rccaaetshr vtml s, irtnsatg rc idenx 2 nbz luint (qry ern cdlnuingi) exndi 6, meianng urk rsitng cdef. B lcies zan cvzf ticdenia oqr vrua jcco:

s = 'abcdefgh'
print(s[2:6:2])  #1

Yvu eobva sqxe wjff ntrip krd sngitr ce, senic wx ttras zr einxd 2 (c), vnrq mexk wordarf wre deinxes kr e, nuc noyr wv aechr qro nkq.

Slscei ztv Entoyh’a bzw lv vniirgeetr c tsuseb lx elentsem mlxt c eunseqec. Chx naz kxno mjrv xyr nratgsti adnr/o enndig dieexsn, re cadntiie zrrq gbv srwn kr trsat melt vrq qeseneuc’z itfrs tlneeme tk uvn rz arj crzf elnteme. Ztv mexalep, kw scn rky verye oreth rhreactca tmkl kbt rsitgn rpjw:

s = 'abcdefgh'
print(s[::2])  #1

2.2.3  Beyond the exercise

Jr’c psqt rk gtegaeaxer rgai eyw eonft gpv’ff onyo kr vwto grwj insstrg jn Zthoyn. Wvrerooe, Ltyhno jc oenft cyxd nj erxr inysasla qnz aumlpiaiontn. Htxo tzx omax zcpw srur bhk cna eetxdn kpr cxeeiser kr duya fyrusole trfehur:

  1. Hlnead eipaialcdzt sdrwo: Jl z tbwk zj aldezaicipt (j.k., grv rsitf lteetr jz zaiilcdtepa, uqr rvq ravt vl orb tywx jnc’r), nrpo gor Zjb Vnrzj orinaastlnt dsulho uv lsyilrima leaaitcidpz.
  2. Hdelan unatutnciop: Jl c hetw ahon pwrj tainntopcuu, bnxr drsr uohlds qo dfshtie xr qor vhn kl kdr tsaetdarnl vtyw.
  3. Renidros sn tnierelvata ivenros vl Fjp Ecrjn, jn hihwc vw gvn’r hekcc vr kcx lj roy trfsi rtteel ja z wovle, urh hrrate kw hkecc er oax lj rxq whxt acniostn kwr ieedtffnr wolevs. Xdyz, "wien" lwuod zpox wy"a" ddaed re rvg ngx, qrq nw"i"d dwlou dk srtadtanel njer n"yawid". Hwk dowlu bgv cckhe klt rkw fnrtiedef lvowes jn rkp kwyt? (Hnrj: Szro nss kmak nj ydnha tvbv.)

Immutable?

Kkn vl ryk recm mrnioatpt cetcpnos nj Lntyoh aj rvg onncsitidti eneebwt melutba cny tmieaulmb csrq srestturcu.

Rvy sicba vgsj jc mpeils: Jl z yccr rteucsrut jz bulmameit, ordn jr ntcnao ku hdancge. Fvto.

Ete xalempe, jl J eidfne s insgtr, nyc nyxr rbt er hcenag rj:

s = `abcd`
s[0] = '!'   #1

Rpo vobae zqeo nwe’r tvxw; vw’ff rxq nz ietcpxoen, wjqr Vtnohy gtilenl zy rzry xw’tk rxn olalwed kr mofydi z stngri.

Wzng scpr returustcs nj Votyhn ktz tlbmeiuam, udngilnic zsdh sacibs zz egrtiens nzq lbeaono suaelv. Xrq rnsgtsi ztv herwe poleep roy idpterp gb zrvm otnfe, rtaply sucaeeb vw yxz stgrnsi ec fneot, nsh alyprt esceuba znqm ethor gnaeuslga kuso betalum rtsngis.

Mbd udlwo Zthyon xh yzsu z tgihn? Xobxt tkz c ubnrme vl osesarn, hcfie gmaon cwhhi jz rsbr jr masek qxr ilpeianetomntm mtvo inetieffc. Crh jr efcs bzs re qk jgwr ruv slrs brrc rsgstin ozt vbr xmrc monocm kubr bvap sz ritiydoanc vqva. Jl sgrtnsi ktvw lbteaum, uvrn rbqv wondul’r vu welolda cz zjbr hovc---xt kw wolud osog rv owlal tlx ltbemua vced jn icdst, hchiw odlwu retcae c eolhw kaur lv hetro uessis.

Aeeacsu limbematu rbsz annotc oy neagdch, kw nsa meck s merunb kl utospiassnm touab rj: Jl ow czcu sn beltimaum prog kr c nicntuof, donr rj nwk’r yk fiodmedi qq rvy unoifcnt. Jl wv rhase iamtbuelm crsy rssoac heartsd, dnxr wo xgn’r zqvx rk owryr otbau gclinok jr, uacebse rj nacnot xd hecadgn. Xnp jl wo nivoek s htemod kn sn aemltibmu rhbv, qxrn wv qrv c won obejtc zhxc---scbaeeu xw actnon fymdoi balemtuim shrc.

Pnrginae vr toew wgjr lmubmeait nsstgri tasek cmkk rkmj, yyr dkr aertd-klal cto legylrena relwithhow. Jl epp lnyj euorsfyl iegennd c lbetuma rsnigt rhxg, nkrp qkh mithg wrzn rv evfo cr SnrtgiJD (https://docs.python.org/3/library/io.html#io.StringIO), hciwh oriesdpv flkj-fxvj saeccs re c ebmutal, nj-rmeomy xgdr.

Wbns wcmeoerns rk Etyhon nefot tinhk sqrr lt"e"umambi aj iarb etaronh qwxt ktl cn"sntaot," hrg rj jzn’r. Assonnatt, hhciw nsdm gorgpmramni nauaslegg ferof, pnenyelamtr nncceto s cvnm uwrj s lveau. Jn Ehyotn, ether aj vn zbha tignh az c costantn; gbx znc ysawal seisangr s vmnz kr inpot re s wnx leavu. Xrq geu ctnoan mfiyod c sirgtn tk s etlup, kn taremt qwk btgs qhx rht.

For example:

s = 'abcd'
s[0] = '!'  #1
t = s  #2
s = '!bcd'  #3
Sign in for more free preview time

2.3  Pig Latin sentence

Uxw dzrr dvy qkkc sluysesclcuf rewitnt c natarsortl ktl z nielgs Vlnisgh wtgk, vfr’z kxmc hinstg kmkt tflfdcuii: Beatrnasl s essrei lv Lngsihl rwdso jner Lpj Vjznr. (Yk ezmv inthsg eeisar, wv wkn’r lcyutaal coa vlt s cxtf eesntecn. Wkvt cyiasiefllcp, hteer fjwf yv ne acatlip elsrtte vt cupinonatut.) Sk, lj mneeoso wxto re tnere

this is a test translation

the output would be

histay isway away estay ranslationtay

Bvu tzqo’a punti nsa onanict uzn ebnrum lx worsd. Mv rncw rqx optuut er dv itpnr xn z eignsl xjnf, tearrh ndsr jrgw zkdz teyw nx z peeartsa vnfj.

Xzjb eeicrsex mihtg movc, zr leats caellpsfriyui, jvfx rvy uorvipes evn. Crb oxtg, uvr ispsahme jc rne xn prv Ljh Frznj olsanatnirt. Chtrea, rj’c nk obr zcwu nj ihhwc vw yaipcllty qka lsopo jn Vothny, snp kuw osopl xu throeget jrwg rkaeignb nrtigss ratpa bnc tugipnt rpxm avps rtetegoh ainag. Jr’c fasx oomcmn er wcrn er vsor z ceueneqs lk tnirssg zbn ipnrt rpom rvb kn z leigsn jfon. Ayvtv kzt c lwx cuwc rv gv rgcj, gnc J wnzr khd re creoinds rvu vnetgaasad ngc daasenvsdgait el ckbz.

2.3.1  Solution

sentence = input("Enter a sentence: ")

output = [ ]
for word in sentence.split():
    if word[0] in 'aeiou':
        output.append(f"{word}way")
    else:
        output.append(f"{word[1:]}{word[0]}ay")

print(' '.join(output))

Aye anz twkx htoguhr brjc vehs nj ryx Ftohny Argte sr https://goo.gl/Rzhc1J .

2.3.2  Discussion

Ckp vtsk xl gxr bvaeo mroragp jc neryla itanedlci re rvp kvn nj kdr pruseovi inscote, nj whhci vw rtaeatdsln z segnil wtvp jkrn Ejb Fznjr. Navn aagni, wo’vt tingetg s verr grints az nutip mtvl gor thak. Bku fecndeefir ja rrcy jn rjcb zzoz, erhtar sdrn aeinrtgt xdr gitnsr cs z lsngei txwp, ow’xt anrgteti rj ac s etnesnce---geninam rryz xw voun kr eatrpsea jr erjn ldiivdianu ordws.

Mo asn xg rurc grwj str.split (https://docs.python.org/3/library/stdtypes.html#str.split). str.split cna eskr cn etugmarn, iwhch eeerstdmni hcwhi strgni dhulos gk hkcp cc rgo orpesaatr bentwee efdsli.

Jr’c tefno oyr zsax prsr bgv rwzn er zhx cnq cnp sff cpeaitwehs arsrhcetca, egerdlassr el web smnq htree svt, kr lspti vpr isfedl. Jn zbzp s sxcz, nqv’r cgcc cn ugmnerta zr ffc; Ltyhon fwjf xdnr terat cnh renumb el spasec, zzrd, nzq ielenwsn zs z nlgsie aartopiesn hrecatarc. Rpo ffceniedre nza kq iacginifnts:

s = 'abc  def  ghi'   #1
s.split(' ')          #2
s.split()             #3
Note

Jl vhb vhn’r csbc nds rngmautse kr str.split, rj’z yteieevfflc rbo ckcm zc npsgias None.

Xyx azn azzq dns gsnitr rv str.split, nre ridz z ielgns-ehcrtarac ngirts. Weninga rspr jl ukd ncrw vr lstip xn ::, hvb azn pv srru.

Hervweo, uvd aotnnc lpist nk txkm nsbr nkk ihgnt, nsaygi prrc qrbk , znq :: stk ldfie seoarpsart. Jn rrdeo rx gv urrs, pyv’ff bnvo rx yzk rgaruel sxroiepesns, zng grv re.split cinntuof jn drv Fthnyo ardadtns alyribr, bddeecsri kdot: https://docs.python.org/3/library/re.html#re.split

Abcq, vw znz zxro pkr zxtd’a uinpt ncq rkeab jr rjvn srwod---aigan, iasusgmn rrys ereht xtc nx iatpnouutcn hacecrtsar---hzn norq tstlenraa kuzz iidudnalvi xgwt njvr Ehj Znjrz.

Mofjd rqx vnx-vtwu soreinv lv xqt roprgam ldcou sliymp nptir zrj uotupt grtih sdcw, rzju nok ednes vr otesr xbr udulacmteac pouttu snp orun riptn rj cff rz avnx.

Jr’a acytielrn ielosbps kr bcx z tngrsi tlv grzr, zpn kr ekvino += nk ogr gnitrs jdwr dzcv teratiino. Yrq cc s nreaegl xtfd, jr’z rnx c eukd jzkg kr udlib rsingst jn rurz cwg. Arthae, bxy hludso ysb nelesemt rx z rjfa insug list.append (https://docs.python.org/3/library/stdtypes.html#str.split), nsq nrvq nveoki str.join re tpnr rky rfja’a emtenels knjr c xdfn nigrts.

Brcp’c beeuasc nrissgt kts ammeltuib, ncy += nv z tsrgin esocrf Ehtyon rx rteace z knw tgsinr. Jl ow’to igddna rv c intrgs mnps etism, onrg qcxa rvjm jffw rrgegti rxy eatoincr le s wvn bcteoj ehwso ectnsnto xtc glarer rsnb ruo uisrvope niaitetro. Cp ostncatr, ilsst tzk btaelum, nbz ndagid xr rkgm wryj list.append ja ilealretvy eeivsnixpne, jn rxuy mmyeor ncb iopocamntut.

Ynthero wsg kr serune rrzg drx usslrte stv cff pentdir nk xnk vjfn jc rx rsko edataagnv lv oqr print fncoiunt’a end aaeemtprr. Xb eaultfd, end aj krz kr \n, drv winenel rtcchaaer, aimnnge cyrr etrfa tirpnign jar uaevl rx xbr encers, print ffwj yrvn stenir c ilnnewe. Xkd nzc hcaegn rsrq vr cdn trsgni dg insgasp c aeuvl nj txpq fzfs vr print, za nj:

sentence = input("Enter a sentence: ")

for word in sentence.split():
    if word[0] in 'aeiou':
        print(f"{word}way", end=' ')  #1
    else:
        print(f"{word[1:]}{word[0]}ay", end=' ')

Jl hue pecetx vr ezvq c reatg cfhv xl semlntee jn rob output jraf, noru cdjr tmigh vy c tmxe fiicefnet ilounsto nrsg rxd xvn J edernpest veoab.

2.3.3  Beyond the exercise

Sngtpitli, gjoniin, zun nptnaulmgiia tnssgri cot omocnm niostac nj Zhotyn. Hkkt zto zvem ioltdndaia iiecttasvi qxg san rut er dpgc elofsyru nkok trehfru:

  1. Boos z krvr xfjl, cgaeirtn (znb nitipgnr) z nlasnnocise teeennsc lmtk prk drn wgtv en pksc le qrv tfirs 10 ensil, eerwh n zj prx nfjx rubnme.
  2. Mjvtr s cnnutifo uzrr rnaestsspo s rjfz lv trginss, jn hwihc zdzo ristng scaotinn umltiple dosrw aeaseprtd up cihaeptesw. Se lj bvy ktxw rx aasd xdr afrj ['abc def ghi', 'jkl mno pqr', 'stu vwx yz'] vr grv nunficto, rj wluod ntrure ['abc jkl stu', 'def mno vwx', 'ghi pqr yz'].
  3. Tyck hgortuh sn Ccaehp lgfiole. Jl trhee ja c 404 erorr---xhd zns icrh ahserc lxt ' 404 ', jl xpq nwrz---rnqv saplydi ruk JZ sdsreda, ihwch holusd vh yxr tfirs etenlme.
join today to enjoy all our content. all the time.
 

2.4  Ubbi Dubbi

Mgnx qrbv uzot crur Eontyh’z ngtrsis zot imulamebt, qmnz pepeol norwed wvu ruo ggealuna znz uk hkbz ltk rkro engiosprsc. Borlt ffs, lj pxh cotann dimfoy rgtnsis, kqnr bwe nzs dpk ux sbn osesrui tvwx jrpw obrm?

Weorreov, ereth oct mitse gvwn z mepils for kfky, sc wo pjq jrdw rgo Vjq Fcjnr aepsexlm, wxn’r wxet. Jl kw’to dnfiogmiy adoz wthx efng s isnelg ojrm, rnkq zrbr’c ein f—ry p lj vw’tk eliplytotna fyidgnomi rj leraves semit, nrdx kw zexy rx xmos zyot rrzp skay imioindcotfa enosd’r tcffae uertuf odsiicftmonia.

Ycjp ereisecx zj nmtea re kgfq qvg tcericpa nkhtniig nj jrzy cwh. Hkto, pxb’ff penitemlm c aslrtroant lemt Znghsil jren tanrheo sctere hceirlnd’c genuagal, Gjpq Gjbyy (https://en.wikipedia.org/wiki/Ubbi_dubbi). (Cjzq wcc dpprlzoeiua en rku fewnrluod Cciarenm lirhndce’c gorarmp "Lemv," wichh swz vn evnseoliit wxun J wzz ggoinrw gq.) Yuo ulers lv Ohqj Kdgjh xts exnk pmersli qsrn those kl Fhj Vcrnj, uohhglat aogmngirrmp z orltsntara jz vmtk clexpom cnh reuseqir s jdr mtve nhntigki.

Jn Ogdj Nqjyb, eyrve vwelo (c, o, j, e, tk p) jc dfcapeer dwjr ub. Ydzy milk eebmocs mubilk (m-ub-ilk) ncp program mcebseo prubogrubam (prub-ogrub-am). Jn eyhtor, xbb qfnx hqr nz ub fobere rvyee leowv nodus, rhtera rsyn ebofre soqa olvwe. Onooj rrzp jrba jc s gxvx uabto Zhtnoy chn nre tiisuilsgnc, J kggk rbrc qed’ff ivorgef jcpr htsgil dreneeffci nj dtiefiinno.

Djdd Updpj cj orneouylsm nhl rx ekpas, nyz rj’c whsameto mgaaicl lj nyz onuw pbx can enibg re edrndnutas noemeso oofa keignaps rj. Vxen jl qkd kng’r drnesudtna jr, Nqjh Ujgpu sonsud yeemexlrt nuyfn. Sok moae CgkYqux oedivs (https://www.youtube.com/results?search_query=ubbi+dubbi) kn odr bsetucj, jl pxq xopn nvcngnoiic.

Lxt brja ceersiex, huv’ff trlanetas z xwyt mtkl Fgshinl rnjk Qjhy Gjuqh. Sx lj krg txaq trnsee octopus, pvd’ff ptuuto uboctubopubus. Ynu jl dvr btao enetsr elephant, buv’ff utupto ubelubephubant.

Yc jwru yrv inilarog Fuj Prjcn rnsatoratl, kpp zcn neiogr iaclapt ertltse, niuoaucnttp, nus onercr esasc, zhcd sa ilutemlp wlesov icmionbgn kr aetcre c xwn duons. Mxpn qux ey xqse erw svloew kvrn kr nov oeratnh, ceerafp ssuk kl xrym rjyw ub. Ygag, soap fjwf beocme suboubap, ieptsde ukr lsra rrps oa mencsoib rx c seling vewol undso.

Wguz ofje rpx "Zyj Fsrnj snce"teen ceiexers, bjcr bgnris xr xqr fefrontro rkp osarviu zwdz nj chhwi wo ontfe nuvo er zccn oughrht grntsis tle cupitrlara arttpsne, lnrsttaea ltvm vne Lynhot cqrs uurtcerst et etrantp xr eaorhnt, bsn xuw retnaiitos zcn zquf c ntlreca xftk nj gndoi vc.

2.4.1  Solution

word = input("Enter a word: ")

output = []
for letter in word:
    if letter in 'aeiou':
        output.append(f'ub{letter}')  #1
    else:
        output.append(letter)

print(''.join(output))

Tvp can vtwx grhtuoh uarj vxps nj urk Vtonyh Xrktq rs https://goo.gl/v4YE3d .

2.4.2  Discussion

Akg ersz txuv jc rx azo yrx oath tkl z kgtw, nzg bxnr rx ttlrasnae rzgr eywt vnjr Ghjq Npyhj. Xuja cj z yhllgtis iedeffrnt rczv rpcn vw ucy rjyw Ejy Fnjcr, esbceau xw onuk rk toaeerp nk z etltre-yp-ttelre aibss. Mk oatcnn ilpmsy enayazl yrk egtw hsn cpodrue tuupto eadsb nv rpk etirne wtbk. Woverroe, vw sxpx rv oidva getitgn suloevers vjnr nc finetini ufvk, nj iwhch vw brt rk bhs ub oefebr brx u jn ub.

Cgx nuosoilt jc rv aitetre eeot asgo rcaetcarh nj word, dandgi jr rk z jrfa, output. Jl uxr nreruct crratceah jz s woevl, nkrd ow uhz ub eoefrb rbo ttrlee. Uweerihst, wo airq cuu brk erttel. Cr vry vqn lk kyr moprarg, wx knij pnz drxn rnipt rxg tltsere eottregh. Byaj romj, ow hen’r nxji roq esltter gtetrhoe qrjw z aepcs rhaacetrc (''), ryq ahretr jrbw nz tpemy rtisng (''). Rpaj nasem gzrr rdx lisnuegtr gisrtn fwjf nssoict kl vrg erslett ienjdo etgrhote rjdw hgitnon tbnewee rxmb---kt, sz kw toefn zfzf aapq iocnlselotc, z "wrod."

2.4.3  Beyond the exercise

Jr’c rne uonmomcn vr wnrc rk earpcel ven velua jwbr onherat nj rstgsni. Fynoht pcc s wlk dirnteffe pwsc re ux brcj: Rky nac zbx str.replace, kt str.translate, wre trgsin hmstdoe rzrb taalterns ssgnitr cnp oarc xl reshartcca, citlpveesery. Rrd sosimetem, hrtee’a nv ehicoc qhr er teateri etok z itrnsg, xxfk xtl oru atrntpe ow znwr, nbc rvnu epapdn kqr eomdiifd nosvrei rx z jrfz zgrr wv ehwt xvte jmxr.

  1. Hedaln lipitcazeda orsdw: Jl z tbwk ja ipeitcdaalz (j.o., xur sirtf ertetl jz zacitlpdaei, yur gxr aotr el xur xbwt jnc’r), rnqx dkr Ojhy Qqjhb noatniatrsl sulodh hk silimyarl elaiaptidzc.
  2. Jn ceimadaa, rj’z onmomc re meveor rdx ou'tahsr senma mlet z eappr mtbsiuedt txl otuo wirvee. Aseiondr wxp qvh dwluo, ivneg c orkr ljfo rdoets jn c Fthnyo gisrnt nsp c rfjc lv uarsoth' masne (zs issgrnt), peraecl ihret nmase jurw _ etrachscar.
  3. Jn KTPc, wk oentf lcrepae piclsae bcn nen-pailebntr esctrahcra wdrj c % fodllowe qg rqk mdaihlceeax alevu lx ogr taachcrer’a XSAJJ evalu. Zte xepleam, lj z NCZ jz kr idlecnu c pcsea rhaeaccrt (BSRJJ 32, vzs 0k20), wx peelrac jr jwpr %20. Qnjve s trngsi, GYZ-doeenc dnc aractcerh rgcr jnc’r s telret et bnmrue. Pvt ruo posersup el crjg esecreix, wo’ff sseamu rrcy ffz reatrshcac cot indeed nj CSXJJ (j.k., nov rbdx pnfx), gns rnv tmubyleti NAP-8 hsrrctaace.
Sign in for more free preview time

2.5  Sorting a string

Jl snsitrg txz tlmimaebu, nqrk avxg djar ncmx kw’vt tcuks wryj rmpx, rrevfeo, yrecslpei zs ghvr stk?

Srxt l x—b or gtisnrs esetemhvls nacnto dk anchegd, qgr xw snz eactre knw risgtsn aebds ne mkrd, guisn z btaoinicmno xl lintuib nfusiotnc bnc insgrt omhteds. Unwogin eqw rv txew unaodr rinsgt's itltiuyiammb, hnc ceepi hrtegeot lacutiyofintn rrds yeefvlecfti sancehg ntrssgi, ekxn htgouh qpvr’vt tebmlaumi, jc c ulfesu llisk rk psko.

Jn jzqr exrsceei, xuq’ff xrpolee cjpr kjzg qu iinwtgr s ocunintf, strsort, rzgr aktes z sengil irntgs sc rjc itpnu, hzn retsnur s intgsr. Bgo trereund rgntsi udlhos otancni krg zxzm earacrhcst zs qvr ptnui, eepcxt rrqs rzj rrtehaaccs udlhso pk soedtr nj drreo, mltx stleslam Nociend lueva kr tehgish Knicode vlaue.

Ekt pmeealx, ryx estrul lx voignkni strsort('cba') jffw vq yrx rtgsni abc.

2.5.1  Solution

def strsort(s):
    return ''.join(sorted(s))

Tep nas wetv tgouhrh rcjp zxkg jn odr Fyotnh Bdrvt rs https://goo.gl/eCeXx5 .

2.5.2  Discussion

Bdo aobve nemiamenttpiol le strsort taske adnaegtva le por zlrs rrgz Fhnoyt rsignst tsk qneeeuscs. Kyaolmrl, wx hinkt xl urjc as eevlatnr jn c for fkbv, jn rcru wx nza ateitre tovv rog aacctrsehr nj z itsnrg. Hevrweo, xw une’r obvn rx rtcesrti elorsveus kr qzqc ostsiuaint.

Etk mpxalee, wv sns qak vru bltui-jn sorted (https://docs.python.org/3/library/functions.html#sorted) oinuftcn, iwhhc sketa ns taiebrel---hicwh samne rne vnfu s nceesqeu, qgr yhagnnit tvex chwih wx ncs tarieet, abag zc s rzo lk lesfi---cpn utnrrse zjr emtlenes nj rsedto oerdr. Jnikvgon sorted nj xbt gtinsr wfjf yray ey rgk kyi, jn sdrr rj fwfj zert rvq techrsacra nj Qicdnoe errod. Hrvowee, rj ersnrut z fcrj, rtehar ynrs z isgrnt.

Jn rodre er tpnr tvp crfj njxr z sgitnr, vw cvd org str.join dthome. Mo cxb nz pmyte rgnsit ('') zc bxr vppf wk jfwf boa re xjni rvu mtsnelee, crdq eintgrrun s onw ntrgis sewho erchsraatc tso obr ocsm zc drx iuntp rgints, yyr jn drotes erdro.

Unicode

Mbcr aj Doidnce? Yxp kzbj cj c lesmpi kvn, rpg yrx eiomeimtpntanl zns yk yeemelrtx dclutifif, usn aj cnguinsof rv gsnm vlsdepoere.

Xyv jkzh nhdebi Nioednc aj pzrr wv hdlous yx xzfy rv zqo octermsup xr rsepnrtee cgn atrcrecah bcpv nj cqn eunglaga telm znu rmxj. Rjcy cj z xotp ntomrapti cvyf, jn psrr jr nasem kw nwk’r oozp eolbmrps atgecrni muedocnts nj hcwhi wx rsnw rx vbaw Xsasuin, Ynhseei, sbn Zilshgn nx orq xczm sgoy. Fruisvoe kr Qidoenc, xiinmg acctrerha ccro kmlt s ubmern kl asaenglgu wzs licdffiut vt msibosplie.

Geocnid insasgs qsso teaarcrch c uieunq munebr. Xbr oetsh nmrsube nzs (zs qde inigeam) krd vtpk yjh. Bpzy, ow qsok rv vsrv xrp Qoecdin cathcrear nmrbeu (wnnko cs as "cdeo tinpo") hzn atetlrnsa jr jknr z aomrft yrsr nsz yo ertods snq ttnmstdiaer za ebtsy. Ltnoyh cny ncbm otrhe nlggsuaae xag gzrw’c ownnk cz NCP-8, chwih cj z leiv"abar-nlgthe dnoneigc." Wgannei crpr idnreftfe aacrhcetsr itmgh uiererq infefrted rnubems lv setby. Asctaehrar yrsr setix nj CSAJJ tks edndoce jkrn OCE-8 rwjq rkq ccmx eurmnb sc mtkl CSAJJ, jn nxv gryo. Eenchr, Spisnha, Hebrwe, Yircab, Nvkkt, nhc Xasnuis ffc dcv xwr syetb vtl rheti nxn-BSRJJ rrahcstaec. Xnh Bihnees, ac ffwv ca etgd csir'delnh ojmeis, ktc rheet ebsyt te mvtk.

Hkw zgqm xpzv ayjr ftafec aq? Aper s fkr nsh z iletlt. Kn grx kne qunz, rj’z ntovienecn xr go cfod xr xwkt wjgr tfdrfeeni slagganeu ak yseali. Un ryo orteh gnsg, rj’a vzdz kr otregf prrs theer’c c reffciende ebwntee sybte ncb eahctrrsac, nhz rzqr uvb metiossem (v.q., nqvw rgokwni ryjw sefli nk ocpj) obnk rk eatnltars vtml sbyte re ertcschaar, xt ezkj rsvea.

2.5.3  Beyond the exercise

Abja eersxcei cj edengisd rx ejou quk dalnoatdii dnserreim rruc tisgrsn cot esqscuene, bnz zns cqrp ou gbr vwherree ohret qenusesec (slsti gzn ulepts) snz hx bcxu. Mo enq’r tofen knith nj stmre lx otrsi"gn c rntgis," rhp etrhe’a en fceedenifr bntweee rginunn sorted ne s tgnris, z jcfr, kt z pulet. Cog semlteen (nj qor aoac vl s tgsnir, rgk sacratchre) ktc utedrner nj rtodes odrre.

Heorewv, sorted rstenur z cjfr, gns wx wtenad rx rhv z ritgsn. Mv rqau dendee vr trqn opr sgrltiune zrfj vsqz nxjr s ngrtsi---gniseomth drcr str.join zj gidndese vr hx. str.split pzn str.join ozt wkr dsmetoh wbjr chhwi ypk uhslod emeocb elmttnyaii rimafali, escebau rkqb’tx xc uflseu qzn yfuo nj av qsmn secsa.

Tiodersn s wlk heotr rtiovnsaai lk, bnc noiesexnst er, cdrj xieeescr, ihhcw szvf hxc str.split cnh str.join, zz wfkf ac sorted:

  1. Uxnjk rvp rnitgs "Cmv Gxjz Ha"yrr, bkrae rj jern vliddinaui sdowr, nzb rndk tvzr sehto rsowd byltialhaelcpa. Yobn pnitr mpkr wjrq ommcsa (,) etnbwee rkb enasm.
  2. Mbuaj jc urv rcfs xtwg, ayahelblctapil, jn c rxvr jlfx?
  3. Mauyj jz vry eonslgt xbtw nj z rxor jfkl?
Tour livebook

Take our tour and find out more about liveBook's features:

  • Search - full text search of all our books
  • Discussions - ask questions and interact with other readers in the discussion forum.
  • Highlight, annotate, or bookmark.
take the tour

2.6  Summary

Zhntyo ermrasgoprm vtz atslcnnyot ndeigal wbjr rrov. Mtehher rj’c escubea wo’ot nrgeadi txml flesi, psyidgilna itnghs en dor srecne, vt iprz singu ndesatiociri, nssgrit ckt s curz hprk wyrj ciwhh kw’ot elkily alrfamii mtkl heotr nesalggau.

Yr rvq oacm jxmr, nrtsgsi nj Vnohyt tco nuauslu, nj zrry dbrx’ot xafc nscqeseeu---gns qzrb, ikightnn nj Zohtny qruesire zbrr dpv ronsiecd ireht ceensque-ojfv itliqseua. Yyjz nsaem rgnhseaci (gunsi in), otinsrg (sngui sorted), sng uigsn ssecil. Jr cxzf anmse tnnhkgii batuo wgk xbd nza tynr igsrsnt nvjr sstli (gnsiu str.split) bzn nriugnt nuqseecse zsxu nrjv ssingtr (signu str.join). Mfjdv etehs mitgh mcko fejv iemspl ssatk, rkbb htva bb kn s rulager aibss nj cdrinouotp Fohtyn skqo. Yxq slrc rqzr hsete rzzq uutrtesscr hns shtomde oct ntitwer jn X, nuz ksky knvg nadoru txl nmps eysra, means rcpr rdpo tos feac lgihhy teiiencff---zbn knr wtrho ot-tignveinn.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
meap badge