0% found this document useful (0 votes)
5 views14 pages

String in Python

The document introduces strings in Python, explaining them as sequences of characters enclosed in quotes, similar to beads on a string. It covers the creation, manipulation, and traversal of strings, including indexing, concatenation, and the use of operators. Additionally, it discusses special string operations and the importance of using compatible data types when performing operations on strings.

Uploaded by

srijarajesh274
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

String in Python

The document introduces strings in Python, explaining them as sequences of characters enclosed in quotes, similar to beads on a string. It covers the creation, manipulation, and traversal of strings, including indexing, concatenation, and the use of operators. Additionally, it discusses special string operations and the importance of using compatible data types when performing operations on strings.

Uploaded by

srijarajesh274
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
otrings in Python 6.1 INTRODUCTION After going through Conditional Constructs in the previous chapter, we will now discuss Strings—an important sequence/collection provided by Python. ‘Think about beads or anything you might string together. You place one bead at a time on to the string, Eventually, you end up with some type of ornamentation—perhaps, a necklace or a tree garland. But the point is that these items are made up of individual beads. Fig. 6.1: String in Real World ‘The same concept of a necklace made up of beads holds true for strings in Python. When you see a sentence, you understand that it is made up of individual characters that are strung together by the programming language you US ‘The language creates a structure that holds individual characters together. So, the Tanguage and not the computer, knows that so many alphabets or numbers in a row (each number being represented as a character) make a string or a sentence. Like in real life, we deal with strings in Python as well. Now the question arises— Where have we seen strings before? Recall the simple programs that we have discussed in the previous chapters. to the user that combines with their name, {A program to dleplay a “ello” onside the Python code for this 7 -— In the given example, the sentence we have typed in print() seing, Even thos ‘He output mess to bes ‘ote wd, he, “Enter Your name’ isa I you see a sentence, Python sees specific number of characters, Similarly, ig displayed 28 ‘HeHofinku' Is again a string, So, we can say thata string, more laves lke a varlable holding characters or alphabets Inside double quotes or single 6.2 WHAT ARE STRINGS Python, a consecutive se single (7), double (°") or triple (" ‘lanactors may tele a fetter, a numb we of characters, which are enclosed or surrounded by ‘quotes, ts known asa string. This sequence of Unicode special character, whitespace or a backslash, A string may he specifi by placing the member ei A the nequence whin quate (supe, delle or triple Python String Fyibon reas sige ots he aawe ax souble tes ple quotes are typleally used for strings that span y_stlng "Python Strnge™ multiple tins, Var example, W the ven example, we ha vle, Mannow ApplowCiapes (whe " 24 sot vale ass ine alo declared fn the 6,9 CREATING STRINGS Stuings an yong the most Ing with the names of frults and! space In between, W indicates space) enclosed Inside slngle quotes * ’, thus {0 the vavlable Fraits Like other lmteger varlables, stelags wamner us ‘perator, op lata types to Python. We ean eveate them by simply enclosing tthavactery tn quotes (single, louble or triple), Sanvetines, triple quotes can be used in Python Unut they’ ane jenetally used to represent multi strings ad doe strings. Aw empty stein is a ys Hhat has character Croat strings Is as simple as signing a value toa varlable. Hor example Het = Mette Wort” python Prot _m—e ‘Congte Soxnce wan PY Baryon 390 set Fe Et Shel Ong Opbon Winn ep fython 3.5.9 teag/e3,9.0:5ef0782, v.1927 64 bit (AMD64)} on win32 patted Type “helpt, “copyright®, “credits” or *Llcense()* foreation ahe"s “eredits® of *llcense(* for nore in >o> strle'tello world! >>> stel ‘HeLlo World? >>> stede"Python Frograming™ Fe an be enced witin vi o> sted 1c out gute bth re vented "eython Programing? [estes Fig. 62 Creating Stings [erent canbe enclosed within single or double quote bath representa sting python does not support a character type—these are treated as strings of length one. Thus, they are also considered a substring, For example, ‘a,b, 'c are all strings of length one. ‘As we know, double quotes and single quotes are used to represent string in Python language and both are interchangeable. But when a string contains special characters such as quotes, we reed to escape them (Le. with a backslash \’ character infront of them to indicate the special nature ofthe character). pifferent ways to include quotes inside a string areas follows: 1. Escape the single quote by placing a backslash before it or use double quotes instead as enclosing quotes. o> ae “This As Meera\'s pen.” 3>> pei hie ds Meera’ pen, Soe petwrite an article on °AI" 333 print) Welt an article on *AI* briefhy. riety. 2. the string contains double quotes, we can use single quotes to represent the string and vice ‘versa, so that we don’t have to escape the quotes. sop cetirice an article on "AI" briefly." >>> printed Weice an article on *AI* briefly. 43. IF there are both single and double quotes in the string, then we do not need quotes; ‘otherwise, it results ina syntactical error. TCIM: An caape sequence character I represented as 2 string with one byte of memory S909 Empty String [An empty string is a string without any characters inside waving length zero, Fig. 63 Creating Empty STDS ‘As is evident from Fig. 63, string str does not hold any value, fey it san empty string, Therefore, Avhen we print an empty string. a blank space gets displayed inthe next line Ifthe statement is very long, then It can be shifted to multiple lines with the line continuation character (\). But i shows the result in the For example, Python 3.6.5 (v3.€.5:158c0932D4, Nat r07:4e) (HSC v.1900 32 bit (Zntel)} on win2 )Meredits” of “License()" for Fig. 64: Implementation of Line Continuation Character" I you wish to display the output in the next line, then the use of escape sequence “\n' becomes mandatory. For example, Tae tet fng_Op Wer Python 3.6.5. (v3-6.2:159¢0832b8, Mar 28 201 16:07:66) se v-1900 32 bit. (nvel)) on wind2 Zape “eopyrtgme®, “creaits” oF "alcense(" for jnore information, > eve ae tess ew oe et tay > tte ae Inns Fig. 6.3: implementatlon of Exape Sequence WP —a— ong Sclece ah Por 1 —=——-— tins i Pen fe cat also se escape sequence \e we e Sequence \t to provide horizontal space in the oufPUt For example, 1 etm ty Fythen 2.6.5 (va.6.s:e59c0932b4, Mar 20 2010, 46) (WSC v.1900 32 bie (Intel) on wind Presse TPEELIRE, “eredLest of “Lewnse()* fo patenag ney > gl lh ae css et ig. 6.6: implementation of Escape Sequence Multline Strings Multiline strings are represented using triple single (“*") or triple double ("* “") quotes. Pye (v3.6.5:£58¢099204, war 2 kt (mntel) } on windz [type "copyright", "credits" or *Iicense()" for sore inforsa GOTH) HS ig. 67: Mating swings “CTM:A string Isa sequence of characters, We can create them simply by enclosing characters in quotes (ingle, double or tiple. 6.4 ACCESSING CHARACTERS (INDEXING) IN A STRING We can access individual characters of a string by using the subscript or Index value, which is known as indexing e—a— Each character it images (Fie 6842) and Fis 680) 1. Rerating through string using for loop ina string is located in diferent slots (like lockers), a§ shown in the fo, | efi | for loop. This is done using the ach character ofthe string can be accessed sequentially using Each character of the string canbe sequentially using en foreumrle | | indexes and iterating overt results in displaying the elements of a string, one chat | Consider 2 string: - SEER EEEE atime. hg oi tr 1 Fig.6.8a) Character Representation ina Sting eevee prised} Each character ina string hasan index value, Indexing starts at and must be an integer, ex operator (quate bracket () retrieves an individual element/character ina string by eal ition of index value, as shown in the following output window (Fig. 69), specifying its posi D> vari = “Helio 55> prise (varil@)) o> print (vast (41) >>> print tvarl(-€1) 2 >>> print vari [-6)) i Fg. 610:Toveing Sting vg Loop jp” Feestasiesy | In the given code, the loop starts from the first character of the string ‘str’ and automatically ends g p> ‘when the last character is accessed, 2, Iterating through string using while loop Like for loop, while loop can also be used for string traversal. Each element of the string is accessed one by one and while loop iterates till the end of the inputted string, which can be | ig. 69: ndex Operator] | | determined using standard library function, len() function. ‘We cannot use float or other types for index as character out of index range will rise an IndexError. Il result in Type Error. Trying to access a \We can start index value either from the left or from the right. Left or positive index starts from 0 and ends with -1, where lis the length of the string and right or negative index starts from -1 to the length ofthe string. For example, eine (stea{inoexdyend = *\0"9 Godse S22 Postivelnder ] 0] l1*1s1*]?]*] >] 0 fart cel Cet tetel-[rype Megntveindex | 12) -1 [0-9 -@| 714] 3] 41412 Here, each element or character ofthe string is associated with an index and can be accessed by ts index value. To access any subscript of a string, we use square brackets along with the index, 6.5 TRAVERSING A STRING Traversing string mens accessing each charac one afer the ake b , racer one ater the other by erating ough the elements of a string using either for or while loop. ° om Fig. 6.11: Traversing Sting using while Loop Here, while loop runs till the condition index suatto bo cetccod * + Morning” D>> print te) Good Hoenig fi 13: Coneatenating Stings If we try to add an integer value to a string, it will generate an error, ie, Typetrror will be ‘generated by Python interpreter in case of incompatible data types, as shown in Fig. 6.14 python 3.6.5. (vi.6.5:t59c0932b4, war 28 2018, 16:07 300 32 bit (zntei)} on win32 type "copyright", “credita" or “License()" for more information b> 2 s'0008 HFracenice ost recent call 13st): File scpyatelitioes, abe ty in coosule> Fae) (SE wt 2) foe ¢4 tine! and tate Fig, 6:14: Covrect Usage of ¥ Operator {GTM You cannot add 't and int ‘objects, To wie operator, datatypes should be the same. 6.6 SPECIAL STRING OPERATIONS String can be manipulated using operators lke concatenate (+) replicate (*) and membership ( enenatn > Sng +g ee eo tye Fig. 612: Common Silg Operations 6.61 Coneatenating Stings Coneatenation refers to creating a new string by adding two strings. “+" operator joins or eateates strings written on both sides ofthe operator and ereates a new sti ans on “—a—a Computer Scene wit tho = singe tno you can use concatenation operator “+ with numbers and strings separately for performing addition and concatenation operation respectively. For example, 6+3=9 addition 6 4/9 = 62" Weoncatenation Similarly, ‘6 ¢3 shall generate an error like 2+ book’ generates TypeError as shown in Fig. 6.14, 6.6.2 Replicating Strings We use * operator to create a new string by repeating multiple copies ofthe same string Hello * ele Helio Helio * ey Fig, 6.15: Replicating Sting using ™ Operator e—a- For example, et of type ‘ste nds of the number types for * rast have thet Don rr repcaon). It cannot work with bert, eter operator CIM: Asterisk oper ee ‘multiplication or one sting type and operands of sting toes. ‘The last statement shall result in an error because has tobe an integer value. strings cannat be multiplied—one operang 6.6.3 Membership Operators yon offers two membershp operators for checking whether a particular character exist the given string or not. These operators are in and not in. In operator: It returns True ia character/substring exists in the given string not n operator: I returns True if character/substring doesnot exis in the given string, ‘To use membership operator in strings, itis required that both the operands used should be of string type, Le ty" not An *nedio! bee steteeny” Doe atelage'ny book doo Stel Te string 16: Membership Operators ‘CIM To use memberslp operator In stings, Its required that both the operands used should be of sting ype I) $$ ce src vn tet ——— Pe nr 6.6.4 Comparison Operators You can use relational/comparison operators (2, < >=. <=,5,!=) to compare two strings. Python compares strings using ASCII rather than Unicode value of the characters. Python starts by comparing the first element from each sequence (character-by-character comparison). If they are equal, it goes on to the next clement and so on until it finds elements that differ. Subsequent elements are not considered. Here, strl is “Mary” and str2 is ‘Mac’. The first two characters from str and str2 (M and M) are compared. As they are equal, the second two characters (a and a) are compared. Since they are also equal, the third two characters (r and c) are compared. Because ‘Y has greater ASCI/ Unicode value than‘ str is greater than str2. po> right" >= "Left eve cnt “tellou™ False >>> "abe" >" True {In ll the given examples, Python compares using Unicode values (called ordinal values). For ‘most common characters, ASCII and Unicode values are the same. ‘The following table shows the most common characters and their ordinal values. ‘Table 6.1: Common Characters and their Ordinal Values Characters ‘Ordinal Values cae a5 to TA toe eto 90 tee Di eo 18 “CTM Python compares two strings. character by character, according to thelr Unicode values unlit finds elements that differ, Subsequent elements are not considered 6.6.5 Slicing Slicing is used to retrieve a subset of values. A slice ofa string is nothing but a substring, This extracted substring (s termed a slice. Chunk of characters can be extracted from a string using slice operator with two indices in square brackets separated by a colon ([:l)- 2—mn- Be ndzstep) hreresend is excluded, ‘returning characters falling between the star in tion through examples. return a slice of the string bY stand this operat Example 1: Consider the fllowing code The first ine of fe code shows a string having all the alphabets in uppercase Python will positon till end=I, Let ws unde See ode bln ol Tole] Feely odd Tz abating 10 extract a slice out of this particular string starting ye second statement is going 1 om ee fs a of 15° position as shown below, from the 6 position and points to 14% position inste jalphabet_string = IIR Sliced string = alphabet_stringl5: [print (alphabet_stcing) print (sliced string) Taleo TeDD Dede Tol [oles Tr [uly puLxTv]z >>> | RESTART: C1/Users/preeti/Appbata, Py | ABCDEFGHIJKLMNOPORSTUVHKYZ | [cursKLa10 Here, as we see, ‘end’ position isto be excluded. Step 1 ensures that all characters from index Position 6* to position 14° are sliced out. Hence, statements 3 and 4 shall give the output as HISKLMo. Is taken as 2,5 shown below the output shal be abtained by extracting to the 14° position but skipping the adjacent element from the @ posit since step value Is 2 ence, the output displayed is G11 Example 2: Consider the given string A= “SAVE MONEY": ETE Ts]atv[el [fo = LY foutveindex | o|1|213]a]sle a] Negative index | -10 | -9 | -# | -7 1-6 | -5 | 4 =i @ ) © ) © j Compe Scene wth Pork —t— Sys NP. Ce onan Notre He faipnaber: string = “ADCOEFGITIRUOPGRSTOVRATE™ Siced string = alpnabet_stringl6:15:21 print (alpnabet_string) Print aticed. sEring) Ld. __t TA ADAG OO MEE ‘siphabetting >>> AS" SAVE Ho >>> Al1:3] ni Here print statement prints the subscript starting from index 1 and ending before index 3,50 st wil print AV (1" and 2" index). poral: 3) ‘sav! ‘Omitting the first index directs the Python interpreter to extract the substring til the second index starting from the beginning, fe, index 0. >>> A (32) *E woner* Omitting the sceond index directs the Python interpreter to extract the substring till the end. of the string, starting from the 3" position. poo AT] "SAVE MONEY" Omitting both the indices directs the Python interpreter to extract the entire string starting for 0 Ul the Last i >>> A [nd ae For negative indices, the Python interpreter counts from the right side, Here, start index is ~2 but end index is not given, so it will start printing from index -2 and will peint all the characters til the end (-2 starting point till index -1). e—_Za-— (9) >>> als-2 the Python interpreter to start extracting the Substring frp, iting the fist index directs tebe cing fom the endothe string the enn the beginning Since the negative index indicates si string i printed except the last two letters. ‘This will print alternate characters from the string, Practical Implementation-3 / Program to input name and print the following patter using string slicing: (if name is ANAND), aceinpattrester any ease: *) Te aegetetease) a) peisetewmlouin) [Link] Ester boy eanes an 6.7 STRINGS ARE IMMUTABLE Strings are immutable means that the content of the string cannot be changed after it Is created, Let us understand the concept of immutability with the help of an example. Typetrror:‘str¥’ object des not support item assignment. Python does not allow the programmer to change a character In a string, As shown in the given example, str] has the value ‘Student. An atempt to replace ‘din the string by ‘p’ displays ‘TypeBrror 6.6 STRING METHODS AND BUILT-IN FUNCTIONS Python provides several bull-in functions associated with strings. These functions allow ws to ‘easily modify and manipulate strings. We can think of functions as being actions that we perform ‘on the elements of a string in our code, Bull-in functions/string, manipulation functions are predefined in Python programming language and are readily available for use. Its syntax String_Object. functiontiane () Let us understand these methods. 4, len()—This method returns the length ofthe string Its syntax is: en(st 3 rs Practical Implementation-4 Write a program to accept a string and display the longest substring ofthe given string having, Just the consonants. Peete ost tows el ieeqese sinseeing ot the pwn Steg haven | oe tea eases. login Reopetniceteiog) laeleogtos fora ie canpatangenys 1 akeiegta or steht in» TE fechatrmaaieomtne scesteto Resists eine (ose aainagens ace Sere ([Sesees exyomenpemttingrtarica recgana rtenl pend) 2109 ees Teintytin Lapa waver apne tytn tn ined lencant Sateelof int fgets Speke 12 characte eB npc NB— ea 2 captlize()—This method returns the exact coy of the string with the frst eter jn vppercase Its syntax is: [Link]() Here, seis the string. For example, >>> str] de> [Link]() releone" "welcome" pop stele! ——— pra mpementation-s Write a program to accept a string (a sentence) and return a string having frst letter of each word in uppercase et ge, ered o “Mees” for se afore CRATER Ape 2p] ssetennnrenrnnnnnnne 3. split()—The split) method breaks up a string atthe specified separator and returns alist of substrings Its syntax is: [Link] ([separator, [maxsplit]]] ‘The split() method takes a maximum of 2 parameters: (a) separator (optional)—ttisa delimiter. The string splits atthe specified separator. Ifthe separator is not specified, any whitespace (space, newline, etc) string is @ separator. (b) maxsplit (optional)—tt defines the maximum number of splits. The default value of maxsplit i -1, which means no limit on the number of splits. computer Seance wih Pen Hi —— SS PE For example, implementing spit Function Here, separator is not specified, so space isa string separator by default. ‘The second argument ‘maxsplit is optional and its default value is zero. fan integer value ‘a’ Js given for the second argument, the string is split into ‘ne1" strings. Fig. 1710) Implementing spit Function 4. replace()—This function replaces all the occurrences ofthe old string withthe new string Its syntax is: Fig. 6.18: Implementing replaced Function 5, find()—This function is used to search the frst occurrence ofthe substring in the given string. ‘The method find() returns the lowest index ofthe substring if tis found in the given string. Ifthe substring isnot found, it returns ~1. ts syntax is: find (sub, start, end) (@) sub parameter: It isthe substring which needs to be searched in the given string. (&) start parameter: It is the starting position where substring is to be checked within the string. (©) end parameter: It is the index ofthe last value for the specified range. 2 —i- Be Tig. 619: mpementng find Function Inthe last statement, the ltter’ois tobe searched from index 11 to 13 (as index 14 is excluded I seareh), Since oes at the 14° postion, it wil result in an unsuecessfl search and shal return =1 as the output 6 index{)—This function is quite similar to find() function as it also searches the first ‘ccurrence and returns the lowest index of the substring if it is found in the given string put ralses an exception ifthe substring isnot present in the given string, ts syntax is: index (substring, start, end) Fig: 6:20: Implementing index) Function 7. tsalpha()—This function checks for alphabets in an inputted string It returns True ifthe string containg only letters, otherwise returns False Its syntax is: [Link]() 3o> print isti-isaapta0) Returns True as no special character or digit is present inthe string. bop print ist dgalpba() Do emia. false Returns False as the string contains special characters and spaces. 8. isalnum()—The method isalnum() returns True if all the characters are alphanumeric, {e, alphabet letters (A-2, a-2) and numbers (0-9). Examples of characters that are not alphanumerl: (space), Its syntax is: string. isalnun() 1H, %, 8, ete Computer Sece wih Python L rags nto For example, sna cx/tsers/cest Fig. 6.21 ementing vainumd Function ‘The given function shall return output as False since the text contains space also (Fig. 621(@)) pete iniamo Fig. 6.21(b: implementing bainumd Function Asis evident from the second example, the output returned is True since the text includes only text and numbers. Isdigit()—This function returns True ifthe string contains only digits; otherwise, returns False. Its syntax is: strsisdigit () poo ste = "123456" 53> print (stel-tsdigit 0) true Returns True as the string contains only digits. >>> ateta'tan bagged 1st position Sop prise (eel daaigit 0) alee Returns False because, the string contains letters and spaces apart from digits. title()—This Function returns the string withthe frst letter of every word in the string in ‘uppercase and the rest in lowercase. Is syntax is: ate-title() be stel = ‘hello 115 all about stains! !* S3> steltitae() "iente Tes ALL About strings!!* Thus, title() returns a version ofthe string where each word is tite-cased. e—_a-— 13. 4. returns the numberof times substelng str OCCUFS In the given string nt() this facto eo narnia den index then searching, starts from index 0nd ends a Me do not give star ‘the length of the str ts syntax [Link] (oubeteing, start, ond) de> trl = tilello Worla! wedle Joo sth count (Heh 10" 12425) 2 de> str] scount(*ilel0"? 3 tower()—This functlon converts all the uppercase letters in the string Into lowercase, its syntax ate dower () por stele "learning BTN do> print (strl lowe 0) earning python Inconverts only the uppercase letters In to lowercase, Ifthe letters are already in lowercase, then it will simply return the string pop stele “learning python” de> print (ate1 Lower ()) earning python {slower() —This function returns True fall the letters in the string are in lowercase, Its syntax ts: str telower () po ated etpyen do> pelneteten.. slo4oe (0) de> ate © *rytion" de> pelnt (ote slower ()) False ‘upper()—This function converts lowercase letters inthe string into uppercase. ls syntax is: str upper boo varies ‘tiolcono! >>> print (varl upper) wevcone, the letters are alrealy in uppercase, then i will simply return the string >>> varl= ‘ie1c0 >>> print ([Link]()) BB 0) rrr sce nent Practical Implementation-6 Write a program to accept a string and print the string after capitalizing every other letter in the string, 15. 16. Sangin Pon {supper()—This function returns True ifthe string is in uppercase. Its syntax is: ate. Supp. bo» stete 77 S33 peine tet Seuppar0) false Istrip()—This function returns the string after removing the space(s) from the let ofthe sting. Its syntax is: str letript) or ste letrip(chars) ‘chars (optional) —a string specifying the set of characters to be removed from the left. All combinations of characters in chars argument are removed from the left of the string until the left characters of the string mismatches. Do> print ([Link]) Greek Ravolution Here, no argument is given. Hence, it removed all leading whitespaces from the left of the string. ppp steDe screen 332 print stea-isteip ins eg Revolution So> str2e “oreen eavotution Do> print ([Link]("==")) ‘Gen Favotutson Here, all elements ofthe given argument are matched with the left of str2 and, if found, are removed, e—a-— sna chart like: pee nee “mer + Me toe ~ eecanis fe Number of 88 rants its Fequensy vereads ane a0 reas tet ase letters [Pe cancs urteese erent /gpoatartocn cee i reed ee Pe marae ees ae Smee erie ett | gwhitespaces from the right ofthe string, ves all the tal 17, estrip()—This funtion emer Inssymtax st rstrip0 exe ratriplets chats (optional) Is string s = of characters in chars argument 8) ecyng the eof caraer 10 BE Femoved rom the ight, removed from the Tight of the string until AN combinations ae right character ofthe ting mismateReS 1 3 peintateneetrip0) ‘reen evotution removed al eading whitespaces from the right ofthe sting, Here, no argument sven. Hence it bon stele “Conte 33 paint gumetsipcee Begute ere, the eters sae pase as an argument is matched from the right of the string and removed from the right of sr. 1B. strip()—this function returns the stringafter removing the spaces oth on the letandthe right ofthe string Its syntax is: [Link]() dee stel =" sotto 285 alk atest srenmasty + Sop Stel ate “ponte 135 aii aboot sTaNGst1* 7 —B—e : Computer Sone wn Pyeae 19, sspace()—This function returns Trve if the string contains only whitespace characters; otherwise, returns False Its syntax Is: [Link]() pestis 33> print stet-isspacea) doe teint python 2p prin str sepace0) 20, istitle()—This function doesn’t take any arguments. It returns True ifthe string is properly tle-cased! It returns False ifthe string is not a"title-cased” string or an empty string. istitle() p> serie “AL beara Python 33> pring [Link]) bee se 7ALL Learn eython* 33 psstie teeiteo) bop se “This 18 8 symbol 3 prantissiatitieg) doo print iiseseie()) Riise 21, join(sequence)—This function re Joined by a string separator. Is syntax turns a string in which the string elements have been Soin (seque: ) sequence—jon( takes an argument whichis of element ofthe s Sequence datatype capable of return sine. This method returns a stng which be conesosus ek tring andthe string separator between each element ofthe string o> stele "1234+ ° Ree EES 22, swapease()—This function converts and into lowercase and vice versa It does not Its syntax is: turns aluppercase characters of the pen tri take any argument. : [Link]() This funtion re 2 String wh al he cases cha >>> stele "helcome™ . aan SUES >> Stetravapcase “pyehont pease) Song @ split the given string using the arian) function 1s used ts the RE STING Sing thy 23, partition(Separator)—: ee ‘specified separator and returns 2 ‘tuple with String functions In a nutshell: rater {a) substring before the se (b) separator itself (o)arbstring ater the seater Us symtaxis een yuired to separ ments 9 fed wed by two empty: (separator) sate a string. Ifthe separator fs not found, it eee ‘strings within parentheses as tuple. returns the string itself fll pee stene tata Sh Renipariies Dasani ring itself, fllowed by two empty strings, not found, soit returns the sing ere, the separator is ooo state THESES, [eee ere marnaearniion ae ee Fig 6.24: Representing Sting Functions Here str2 is separated in three parts: (a) substring before separator, Le, Hard: 6.9 OTHER FUNCTIONS Oar fat, wot | Inthe internal storage or memory of the computer, characters are stored in integer value a A specific value is used fora given character andi is based on ASCI values. There are different (0) substring ater separator ie," | numbers assigned to uppercase and lowercase letters. Fig, 622: nplemenngendswith Function ‘The following example exhibit the implementation ofthe given two functions for character encoding: Ghaades | 0wo | Kw? | vor AsCiValues | 480057 | 65t090 | 97 to 122 | adores io rer ing —e 0 1. ord(Q—ths function returns the ASC/Unicode (Ordinal) of the character sa: endoith()_rhsfuncin ens Tre thegben singed withthe speeds, | poy a Siherwis, returns Flee | eters Its syntax is: * 2. ebu()—hisfuncton etumsthe character represented by the nue Unicode/ ASC number 25. startswith()—This function returns True if the given string starts with the specified; substring: otherwise it reterns False Its syntax is: Fig. 6.22:Implementing artswithd Function Computer Scene wit Ptr MEMORY BYTES restore, double oF te) ence HITE ers cust ingio asec in Sf — + Srncenremnsn ees on a spies of the same string. operator rratng mune stn stint Be nse 30 esa etna gve si 7 ee renee faa ont 2 pecs tan Be 0 > Reece ne ET asc vales er, xcersng tote racer by are worn characte =Y fa tbe changed afer it has been creates, he sing sin thon. ng with st sin fron for wot fir ete capa ot: f the words in the sting WINE: sate case characters esses ered tou rs a cepy ofthe SME sep asthe dliiter string a cer netod te pe sing re as OtHENWise, i FeAUENS Fae ) etna ret Tae thc 2 State whether the following statements are True or False, (3) $55 and 555 are the same strings in Python, (0) Prthon allows stings tobe enclosed inside triple quotes. (©) You can use only for oop for string traversal (6) Stings mutable in nature. (6) steafy sal return all the characters starting fom sti tl sty}. UN Both the methods index! and find) return the in ‘ccuring inthe given string nex vale ofthe first occurrence of 3 substring (e) pw tion method of string in Python returns the output 36 st (%) * operator can be applied to both integer and string values, (0) Spaces the defaut delimiter given in spit function. i towert method converts the uppercase eters in a string to lowercase, (1 wanton) method of string in Python shal aways vide the main sing nt 3 substrings. 3 Muttple Choice Questions (Meas) (2) What wil be printed on executing the following code? new_str [3] = "st print (new ste) (snow (i) snow worta (i sn0e wo) (i) error Ba (2) Which fhe ooming statement wil return the asthe character of tng? veeateutotaghendeesti8 3S @orrise (i sect 3) > eee WIE W see(-3e 9 tw ste: =33 7 ces oer nerten cS (0 Which of the fotowing operators cannot be ue with tring Python? 2 soot tron pms toh el oe (i) notin w+ wn a (3) Which fhe toning operations ona sing wil result in an err? () sevtiox"s3 (i) veetHoN + 20 ei aekues sy (ii) "PyTHON* + =20" (iv) "PYTHON" + *LaNguace” re (6 Adena he nat singin Python () Helton (i) *Haniow 2 Faint Danks aro ing contain some contiguous characters om ey (8) Hette (0) None ofthese a cictonrouestevng and ang whitspacs ftom a ghen sting (1 Wich te fotonng operators is sed forthe coneteation of to segs? 8 pcton tere sedi o- a" (c) meters sing nes fromthe igh tas rom rte, ce @: oy {a} trdex value ina string should be of : ~TPe (e) Te asouaue 4's function returns th o- 1 ASC/Unicode value character. (e) Accessing each and every element a strings termed as Ub) Trestatement >>> (0 The statement u 2) shal resutin salen so 38 OSU, jong operation takes another third parameter, which is optional and specie % w function retuns te sting with the fis letter of every word inthe 8 Uppercase and the rst in ouerese {€) Which of he fllowing functions wit (i) count) Feturn the total number of characters in 3 sting? (i) tent) (i) indext) (i) Alot these (6) Wich ofthe following functions i se (0 isatohac) "for checking whether a sting is containg digs only? Git satnum() (isc) Ui) None of these (1 What willbe the output ofthe given Python code? stel= "6/4 print wa (iy see wis fiw) 678 Stags n et ————________ a ——8-

You might also like