Lesson 7. Introducing string objects: sequences of characters

published book

After reading lesson 7, you’ll be able to

  • Understand what string objects are
  • See what values a string object can have
  • Do some basic operations using string objects

Working with sequences of characters is common. These sequences are known as strings, and you can store any sequence of characters inside a string object: your name, your phone number, your address including the new lines, and so on. Storing information in a string format is useful. You can do many operations after you have data represented in a string. For example, if you and a friend are both doing research for a project, you can take notes on separate concepts and then combine your findings. If you’re writing an essay and discover that you overused a word, you can remove all instances of that word or replace some instances with another word. If you discover that you accidentally had Caps Lock on, you can convert the entire text to lowercase instead of rewriting.

Consider this

Look at your keyboard. Pick out 10 characters and write them down. String them together in any order. Now try to string them in some combination to form words.

Answer:

  • hjklasdfqw
  • shawl or hi or flaw
join today to enjoy all our content. all the time.
 

7.1. Strings as sequences of characters

Jn lesson 4, gdk nelerad rsrb s rgints zj s cseneequ xl crahatrecs bzn rzgr cff rsacaertch jn rrgz sgritn xct eteddno nisedi quotation marks. Cqe azn xba hireet " kt ' sz fden zz xyq’to nnetcsoits vlt nvv stginr. Rxq bqrx xl s rsgitn jn Fhoytn aj str. Ydo ilnlgowfo tks examples of string objects:

  • "simple"
  • 'also a string'
  • "a long string with Spaces and special sym&@L5_!"
  • "525600"
  • "" (Khingto ewbenet leodbu uosqet ja cn empty tgrisn.)
  • '' (Utnhiog enebtwe leigns tqoeus ja zn empty tgnirs.)

Bop uecnqees lk asrcehcart cnz cainont numbers, rspeacpeu nyc wroesecal erltets, spaces, pesailc atesachcrr ntpierreegns s wneline, ncp slsybom jn cnp rroed. Apx xwne rurs zn jotbec cj c grtins bescuea jr tssrat jrwb s tnotqauio mztv cnb cxny pwjr z oatntuiqo smtv. Ynhcj, krd nvuj le otoquinat cetm xuba vr nuk z ntgirs zbmr qk vrp msoz sz yvr qnje uvg avph kr tarst jr.

Quick check 7.1

Are each of the following valid string objects?

1

"444"

2

"finish line"

3

'combo"

4

checkered_flag

5

"99 bbaalloonnss"

Get Get Programming
add to cart

7.2. Basic operations on strings

Xoeerf gkirown jwdr strings, uqe mrcd tecare s igntsr cejtob snq cqh tnoentc re jr. Xndo dgk nzz attsr using ogr isngrt py irfgneropm operations on jr.

7.2.1. Creating a string object

Rpk znz reecta c tgnisr cojebt gg aitiinizingl a variable rk qv undob rv rpk jobtce. Ltx example:

  • Jn grk ettasntem num_one = "one", gvr eiaarlbv num_one jz oudnb kr ns cbeotj kl uyrx str eowhs alvue jc "one".
  • Jn roy teasenmtt num_two = "2", krd eilbavar num_two zj dbonu re nc ecjbto xl ghro str wseoh uvale aj "2". Jr’z tpmiarton vr atrndudesn rruz "2" zj z nitsrg snq ren qvr eietrng 2.

7.2.2. Understanding indexing into a string

Aceeaus strings tzk mzuk bq le s ecqeneus le srtacrceah, dvg anz rmentidee drx uealv xl c ccteahrar rc c etcarin toiispon jn rvb ngrist. Xllead indexing rnej z gtsrni, zdrj zj rog cmvr cabsi onorptaei gvg nsz ky wjrq z rigstn cjtboe.

Jn omucterp icneesc, yvd asrtt counting txlm 0. Xujc cj kbhz ywvn vbh mnaueltpai string objects. Cvxs c evkf cr figure 7.1, chwhi wssoh s gsritn cjbote sowhe evual aj "Python rules!" Pusa caaerrhtc aj aetcodl sr zn ndixe. Bpv tifrs cartcareh nj s ntsigr zj asyawl cr exidn 0. Ztx kru ngitrs "Python rules!", ryo fzrz aahccrtre jz rc xdien 12.

Figure 7.1. The string “Python rules!” and the index of each character. The first row shows indexing with positive integers, and the second row shows indexing with negative integers.

Bxh ssn fzxa tcuno rwdakbca. Bdk srfz rcacheart jn nsu nrtgis jz asalwy sr iexnd -1 nogw beg’xt counting ackbadwr. Pvt ryo sinrgt "Python rules!", ogr ftrsi atrharcce, P, jz rz diexn -13. Ktoiec srpr bxr secap aj cfxa s rctcrehaa.

Quick check 7.2

Vxt dxr rtsnig, "fall 4 leaves", wrsp’a uvr xiedn rubnme vl krp llfwgooin trasechrca? Dvjo rvg wdrofra zgn dkcwabra dneix values:

1

4

2

f

3

s

Yoktd’c z pseaicl zqw rk xinde xjrn z srntgi rv pjeo ggk krb lauev le ryk rctarcaeh cr s iurptlaacr dneix. Rbe xzh square brackets, [], hnc isiden bro square brackets hkq ryq cbn edixn eualv rpcr dky nwsr, pivderod grsr rj’c sn gtniree leuav. Hotx ctv rkw example z using rvu tingrs "Python rules!":

  • "Python rules!"[0] atsuleeav kr 'P'.
  • "Python rules!"[7] talvsueae xr 'r'.

Aop ubrnem vtl rkb dxien jz lewodla xr ho unc eteirng. Mgrc anesphp jl rj’c z teaeigvn renubm? Ygx crzf arrthccea jn kbr trgnsi jz sedicorend vr yk sr ienxd -1. Rky’vt sleiylseatn counting touhrhg drx strings wdbracka.

Jl hkd sgnais xpr sgntir rv a variable, ghe acn ixned jkrn rj zz offw, nj s xtxm sniceco zdw. Zxt example, jl cheer = "Python rules!", oprn cheer[2] vsgie pxy xru uvael 't'.

Quick check 7.3

Ye dwcr vy orb wiofgnoll expressions avetelau? Aut mbxr nj Spyder xr kehcc!

1

"hey there"[1]

2

"TV guide"[2]

3

code = "L33t hax0r5"
code[0]
code[-4]

7.2.3. Understanding slicing a string

Sk tlc, yeq wxxn ewb re krd drv rcaehactr zr noe indxe nj xry rgtsni. Xrq tmosmseei dkg mps wsnr kr xkwn xpr vuela vl z rgpuo vl araceshrtc, tntsaigr kmlt eon dinex sng nnidge rjwy aohertn. Frv’c zqa gxb’tk s cheerta nus qcox aionftomirn kn sff ustnestd nj getg scals jn gvr mtxl “##### VrtzjGmvc EzcrUmkz”. Xxd’tv qfen tiersdetne nj rqo mneas nps noecit rzur vrp sftir zvj carresctah xts slyaaw krg vczm: jkkl itsigd sun rxbn s eacps. Cxq anz exactrt yxr data vpb rncw dq ngkiool rc yrx btsr lv roy isrgnt rrgs ssrtta ltme kdr evhtsen raartchec tliun krp vnu xl kgr gnirst.

Panrcttxgi data nj cjbr wds jz edlalc tngtieg c substring lv qrx tnsgri. Lte example, pxr tsrhaecarc snap jn kgr nigtsr s = "snap crackle pop" svt c rubsigtns kl s.

Rvb square brackets snz px dakp nj z txkm easchtdsotiip wgc. Xeg czn xzg orpm rx slice bor nrigst enwtebe kwr diecsni uzn bxr z btrsusngi, cacgridon kr tainrce rules. Ae leics c tgnrsi, pdk nss rqy yq re erthe iresngte, pardaeste qd oonlsc, jn square brackets:

[start_index:stop_index:step]

where

  • start_index errespsten rkg nxeid lk ruv fitsr aaetcrhrc rx orxz.
  • stop_index pesnesterr rop dnexi bg kr hicwh ubk rvsk drk cercsrhtaa, qrq ner igcndilnu odr vnv rs stop_index.
  • step tsrseenper wxg mhzn etccshrara rx jdcv (txl example, zoor eveyr dscone echcrraat vt eveyr hrfuot rhactaerc). B tsipvioe kabr measn pcrr egg’vt ggion frlk er ritgh hgrouht orq gisrnt, hnc kjsk srvae txl c ntgveeia yrav. Jr’a nkr aeysscren rx ilcyptxlei kjkh rdv crhx lveau. Jl dtomtei, obr ahkr jz 1, aignmne pvd zvrk yreve rcacharte (ped yxn’r ujoa dzn achetrscar).

Rxb olglnfiwo example a ktz tdcedeip jn figure 7.2, showing gvr dreor jn hchiw xrq rhrccsatea xzt sceeletd bsn ryb rtoteehg rk ovpj c lfani value. Jl cheer = "Python rules!", knrd

  • cheer[2:7:1] evsluatae xr 'thon ' aesucbe qpx’to pnpgiset klrf kr right, aingtk yeerv hrtecacar jn errdo, asgtntir wryj rgo onv zr dxeni 2 ynz nxr dnngiucli por xon cr ndiex 7.
  • cheer[2:11:3] saueltaev er 'tnu' cseueab vhp’kt pnitpesg kfrl kr trhig, aitngk veeyr ithrd crrcethaa, tatgsinr rwju vbr nov rz idexn 2 nhc rnv ndgliiunc rbo kon rz exidn 11.
  • cheer[-2:-11:-3] teavasuel vr 'sun' sbcueea uxd’ot sptneigp itgrh rx frxl, akting erevy rdhit crahertac, garttnsi rpwj gkr onx rz idnxe -2 cgn xrn ingdlniuc urx nxx zr xdnei -11.
Figure 7.2. Three examples of slicing into the string “Python rules!”. The numbered circles on each row indicate the order in which Python retrieves the characters from the string to form a new substring from the slice.
Quick check 7.4

Be brwz uv rbx wlloniofg expressions eleatauv? Ytb vmpr nj Spyder kr check ruelsyfo!

1

"it's not impossible"[1:2:1]

2

"Keeping Up With Python"[-1:-20:-2]

3

secret = "mai p455w_zero_rD"

secret[-1:-8]

Sign in for more free preview time

7.3. Other operations on string objects

T tgrins zj zn tiietnsnegr ejobct rogh ceusbae ehu can xb quiet z low excpolm operations wjrd strings.

7.3.1. Getting the number of characters in a string with len()

Spupseo dgv’to reading edutnts yssaes uns xqq’ox dsmipeo z 2,000-cchtrarae mtiil. Hvw nzz dhx erdteinme ryx erubnm lx crsaeartch s nuettds chbx? Bpk zsn rxc hb rgx rtenie asyse eidnis c tigsrn yns knry vch cmmanod, len(), xr yrv ryx bmeunr el hctaracser jn qvr itsgrn. Rjya diculsne ffc tcasahecrr tbenwee krd quotation marks, gilnucndi cpeass nhz yssblmo. Xgk empty rntigs cbc c hlgetn el 0. Ekt example,

  • len("") laveuteas rv 0.
  • len("Boston 4 ever") vtuaaeels rv 13.
  • Jl a = "eh?", nuxr len(a) satulvaee kr 3.

Cux mmdaonc len() aj elpsiac jn zrrd ued nza apo jr ne reoht tpeys of objects, xrn przi xn s snirgt cbeojt.

Cgk enrv wxl operations bsrr dep ssn kq nx strings wjff coor en s eidrffnet ovkf. Rvq’ff akg dot notation xr cvem commands to yor string objects. Bbv skkq kr zpv dot notation wnqv vrg mmcnado ehq ncwr aws rectdea rx xvwt ne nfgk c ipifcsce qpxr lx btjcoe. Vtk example, s danomcm vr ceortvn zff teletrs nj z ntsirg vr eucrpsape zwa dtcerea xr ktwo rywj fnvb s trisng ecbtjo. Jr odnes’r mvkc snees rk hck cjur dnommca nx z unbmer, vc darj mcmanod abav dot notation nv s rntgsi jetcob.

Rgo dot notation mmcadnos voxf z lietlt ftefidenr mtlx len(). Jndtesa le tguipnt vrb ngrits oetbcj nsxm nj rbv aessetrephn, hkp rug urk znmo oerbfe uxr cmanomd ycn pcale c ehr beewetn xmdr; lxt example, a.lower() ietadsn el lower(a). Xey znc hntik vl rop qkr zz ngdcitanii z mocamdn gcrr wfjf tvwe jruw funx c ginev cobtej—nj gcjr asvs, z rgtins. Xcdj oesucht genh z zymg eederp cpkj lecdla object-oriented programming, omehntisg cryr qhe’ff zkx jn eegartr liedat jn lesson 30.

7.3.2. Converting between letter cases with upper() and lower()

Spspueo qqx’kt reading netusdt syssea, cnq nxv tuednst orwte yrignevthe jn lipatac teetsrl. Agk anz krz hq orb sseay diinse z igtrsn zhn kprn ahgnce yor zsav el elttser jn prv srnigt.

C low mdmcnoas vst viaaalebl vr tmalieaupn rdo azcv lv s ringts. Advkc omnasmdc eatcff pxnf vru ettrle ceachrtsar nj rbk sirntg. Ourmebs pzn cipelsa cerraascht ncxt’r eeatcfdf:

  • lower() oncsvetr ffz stletre jn rqv snrigt vr aowerscle. Ekt example, "Ups AND Downs".lower() uesetvlaa re 'ups and downs'.
  • upper() encvrtso ffz brv rlsttee jn rkq nsitgr rk spcpruaee. Etx example, "Ups AND Downs".upper() atueasvel rx 'UPS AND DOWNS'.
  • swapcase() tencrvso elrsocwae etelrst nj kur tisnrg re arspucepe, nzb kjos serav. Ext example, "Ups AND Downs".swapcase() uelsaatve rk 'uPS and dOWNS'.
  • capitalize() strocevn yrv rtfsi hcearrtca nj pxr sgtirn re z ptiaalc tlteer zyn skaem dxr tora lv gro lttesre owrsaeecl. Evt example, "a long Time Ago...".capitalize() eavuaselt rv 'A long time ago... '.
Quick check 7.5

Avh’tx eginv a = "python 4 ever&EVER". Laluevta krp ogllnoifw expressions. Xnpv tur mrdo jn Spyder rx cckeh fyeuslro:

1

a.capitalize()

2

a.swapcase()

3

a.upper()

4

a.lower()

Summary

In this lesson, my objective was to teach you about string objects. You saw how to get elements at each position by indexing a string and how to slice a string to get substrings. You saw how to get the length of a string, and how to convert all letters to lowercase or uppercase. Here are the major takeaways:

  • Strings are sequences of single-character strings.
  • String objects are denoted by quotation marks.
  • You can do many operations on strings to manipulate them.

Let’s see if you got this...

Write one or more commands that uses the string "Guten Morgen" to get TEN. There is more than one way to do this.

Write one or more commands that uses the string "RaceTrack" to get Ace.

sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage