0% found this document useful (0 votes)
7 views24 pages

Chapter 9 String Manipulation

This document covers string manipulation in Python, including traversing strings, string operators, and string slicing. It explains the immutability of strings, basic operators like concatenation and replication, and membership and comparison operators. Additionally, it provides examples of string slicing to extract parts of strings using indices.

Uploaded by

shankgv67
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)
7 views24 pages

Chapter 9 String Manipulation

This document covers string manipulation in Python, including traversing strings, string operators, and string slicing. It explains the immutability of strings, basic operators like concatenation and replication, and membership and comparison operators. Additionally, it provides examples of string slicing to extract parts of strings using indices.

Uploaded by

shankgv67
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
pT 9 String Y ; _Manipulation Chapter 9.1. Introduction 92. Traversing a String 93. String Operators 9.4 String Slices 95. String Functions and Methods INTRODUCTION You all have basic knowledge about Python strings. You know that Python strings are characters enclosed in quotes of any type — single quotation marks, double quotation marks and triple quotation marks. You have also learnt things like — an empty string is a string that has 0 characters (ie, it is just a pair of quotation marks) and that Python strings are immutable. You have used strings in earlier chapters to store text type of data. You know by now that strings are sequence of characters, where each character has a unique position-id/index. The indexes of a string begin from 0 to (length ~ 1) in forward direction and -1,-2,-3,...., length in backward direction. Inthis chapter, you are going to leam about many more string manipulation techniques offered. by Python like operators, methods etc. NE s COMPUTER SCIENCE Witt py m1 oa HON 9.2. TRAVERSING A STRING ‘You know that individual characters character. Using the indexes, you can e to. iterating through the elements of a string, traversed through strings, though unknowingly, v alk {for lops. To traverse through a string, you can write a loop like: mane="super” __ ns papi ese ISLS) through string name n yr BY ER NIKHIL Sif ml of astring are accessible through the unique index traverse a string character by character. Traversing % ‘one character at a time. You have ey when we talked about sequences along“! ei nection for chin name : rece by character. ravine cael i print (ch, “t, end="") ey string, one chereaer ot BI 8 The above code will print : Sting one char) Reed ay oncos s-u-p-e-r-b- ‘The information that you have leamt till now is sufficient to create wonderful programs j manipulate strings. Consider the following programs that use the Python string indexing , display strings in multiple ways. 9.1 Do i rogram string] = input( "Enter a string :") print ("The", string1, “in reverse order is:") dength = 1en(stringl) Since the range() excludes the number ram to read a string and display it in reverse order - display one character per line. ot create a reverse string, just display in reverse order. for ain range(-1, (-length—1), -1) : ‘mentioned as upper lini, we have print (stringi[a] ) inode ne Sample run of above program is : | Enter a string : python The python in reverse order is: A ° h t y P 9.2 Program to read a string and display it in the form : Jirst character last character second character second last character For example, string “try” should print as : ty ror yt wea 9: STRING MANIPULATION seringt = input “Enter a string :») length = len(string) ix for a inrange(-1, (~Length-1), -2) , print (stringi[i], "\t", strin, 1 print e1[a]) sample run of above program is : enter a string + python f 93. STRING OPERATORS In this section, you'll be learning to work with v. strings in multiple ways. We'll be talking about basi in and not in and comparison operators (all relatio 's operators that can be used to manipulate ic operators +and *, membership operators mal operators) for strings. 93.1 Basic Operators The two basic operators of strings are : + and *. You have used these operators as arithmetic operators before for addition and multiplication respectively. But when used with strings, + operator performs concatenation rather than addition and * operator performs replication rather than multiplication, Let us see, how. Also, before we proceed, recall that strings are immu you perform something on a string that changes it, rather than modifying the old string in place. table i.e, un-modifiable. Thus every time Python will internally create a new string Sting Concatenation Operator + The + operator creates a new string by joining the two operand strings, eg, “tea"+ “pot” will result into Two inp sings oie (concatenated) 0 form new string ‘teapot’ Consider some more examples : Expression will result into Fp an "a" ro" ‘a0 "123 +'abe ‘"123abe ComPurer science FR, NIKHIG Si 274 ce internally. Python creates a new string inthe mg of first string operand followed by the ingi™) characters of second string operand. (see below) a) - GEEEEE [New string erated by Joining Sting operand Let us see how concatenation takes plat by storing the individual characters [e String operands Original strings are not modified as strings are immutable ; new strings can be created 4, existing strings cannot be modified. Caution+ Another important thing that you need to know about + operator is that this operator can wo, with numbers and strings separately for addition and concatenation respectively, but in the sam expression, you cannot combine numbers and strings as operands with a + operator. For example, # addition - VALID # concatenation ~ VALID But the expression 243 is invalid. It will produce an error like : Traceback (most recent call last): “The + operator has to have bth ‘operands of the same type File "", line 1, in ater of, number eee 243 addition) or of string types (fr Typetrror: cannot concatenate'str' and'int objects ‘mubiplication). tt cannot wot with one operand as string and Thus we can summarize + operator as follows : fone as a number. ==! Table 9.1 Working of Python + operator Operands’ data type _ | Operation performed by + Example numbers addition 949518 string concatenation "9" + "9" = "99" String Replication Operator * The * operator when used with numbers (i, when both operands are numbers), it performs multiplication and returns the product of the two number operands, To use a" operator with strings, you need two types of operands ~a string and a number ie 38 number * string T string * number | BY ER NIKHI STRING MANIPULATION 275 oer where string open tols the string to be replicated and number operand tells the number of times, itis to PE |; Python will create a new string that is a number of repetitions of the ftring operand —, is oTemEd 3* "go!" For replication operator *, return Input strings repented pec Python creates a new string that will Ae of tines forma nova ne is a number of repetitions of the 'go!go!go! ‘input string. =a Consider some more examples : Expression will result into "abc" * 2 “abcabe" Coutiont Another important thing that you need to know about * operator is that this operator can work with numbers as both operands for multiplication and with a string and a number for replication respectively, but in the same eXpression, you cannot have strings as both the operands with a * operator. For example, 2*3=6 # multiplication - VALID 7t*3 = "222" # replication - VALID But the expression hares ayre sgt “The* operatorhas to either have both operands of the number is invalid. It will produce an error like : eerie lea crane yee oye string type and one number type peta n 3 “(for replication). tt cannot work with both operands of string Traceback (most recent call last): File "", Line 1, in ge ge TypeError: can’t multiply sequence by non-int of type'str’ Thus we can summarize + operator as follows : Table 9.2 Working of Python * operator Operands’ data type _| Operation performed by * Example numbers multiplication grgei8 string, number replication ee number , string replication ate ‘COMPUTER SCIENCE TERA HIL ; 276 9.3.2. Membership Operators i ti two membership operators fo a ked about them in pre’ I sequence types). These aren ings (in fact for al gi briefly. Let us lear about gi! ee et wious chapter, not in. We have tall ings. operators in context of string: Recall that : as exists i : 78 i Rotums True if a character or a substring exists in the given string ; False otherwise N st ccven string: tin Returns Tru ifa character ora substring doesnot exist in the given string; False otherwise no! Both membership operators (when used with strings), require that both operands used wi them are of string type, ic « in not in 84 "12" in "xyz" "12" not in "xyz" Now, let's have a look at some examples : ‘at in “heya” will give True "Jap" in “heya” will give False “Jap” in “japan” will give True “Jap” in "Japan" will give False because j letter’s cases are different; hence “jap” is not contained in “Japan” will give True because string “jap” is not contained in string “Japan” "jap" not in "Japan "123" not in*hello" _will give ‘True because string “123” is not contained in string “hello” "123" not in "12345" will give False because “123” is contained in string “12345” The in and not in operators can also work with string variables. Consider this : >>> sub ="help" >>> string =‘helping hand >>> sub2 = "HELP! >>> sub in string True 99> sub2 in string False >>> sub not in string False >>> sub2 not in string True RING MANIPULATION BY ER NIKHI wo 277 3 Comparison Operators 9 pythow’s standard comparison operators, : all relational } strings also. The comparisons using 4 perators (<, <=, >, > these operat ea HH te i erators are based on the standard ter-by-character comparison rules i i © Sands Maral iP les for Unicode (ie, dictionary order), ‘mus, you can make out that will give True will give True will give True will give True will give False (letters' case is different) will give True (letters’ case is different) Equality and non-equality in strings are easier to determine because it goes for exact character matching for individual letters including the case (upper-case or lower-case) of the letter. But forother comparisons like less than () or greater than (>), you should know the following piece of useful information. ” Asintemally Python compares using Unicode values (called ordinal value), let us know about some most common characters and their ordinal values. For most common characters, the ‘ASCII values and Unicode values are the same, , , The most common characters and their ordinal values are : Table 9.3 Common Characters and their Ordinal Values Characters | _—__—_Ordinal Values ‘0 to 9" _| 48 to 57 ‘A to 'Z! 65 t0 90 | ‘al to'z! 97 to 122 Thus upper-case letters are considered smaller than the lower-case letters. For instance, aOR will give False because the Unicode value of lower-case letters is higher than upper case letters ; hence ‘a’ is greater than ‘A’, not lesser. “ABC > ‘ABs will give True for obvious reasons. ‘abe <='ABCD' willl give False because letters of ‘abc’ have higher ASCIL values compared to ‘ABCD’. ‘abed >'abcd' —willl give True because strings ‘abcd! and ‘abeD” are same till first three letters but the last letter of ‘abeD" has lower ASCII value than last letter of string ‘abcd’. Thus, you can say that Python compares two strings through relational operators using character-by-character comparison of their Unicode values. a e BY ER NIKHIL Sif COMPUTER SCIENCE WITH py, i 278 m Character kes a single character and retums the ¢g final/Unicode Value of a Single Tes, ) that tal Determining Ordi .d as per following format : Python offers ponding ordin ord() a built-in function ord( ial Unicode value. It is use' i les + Let us see how, with the help of some examp! a © To know the ordinal value of letter ‘A’, you'll write ord(’A) and Python will retum ty corresponding ordinal value (see below) : >>> ord('A’) 65 But you need to keep in mind that ord) function requires single character string only. You ma, even write an escape sequence enclosed in quotes for ord( ) function. The opposite of ord) function is ehr(), ie, while ord() returns the ordinal value of a characte, the chr() takes the ordinal value in integer form and returns the character corresponding to tha, ordinal value. The general syntax of chr( ) function is : chr() # the ordinal value is given in integer Have a look at some examples (compare with the Table 9.3 given above) : >>> chr(65) 7” >>> chr(97) ig i 9.4 STRING SLICES | As an English term, you know the meaning of word ‘slice’, which means — ‘a part of ’. In the same way, in Python, the term ‘string slice’ refers to a part of the string, where strings are sliced i using a range of indices. That fora string say name ifwe givennel #:] wheen — _STNESTSSaE and mare integers and legal indices, Python will return a slice of ‘the string by retuming the characters falling between faryanaust en contain some indices m and m - starting at 1 n+1, +2... till m—1. Let us ta ee eae understand this with the help of examples. Say we have a string namely word storing a string ‘amazing’ ie., o 1 2 3 « 5 6 word BT ome] Seer len [ce J 46 5 4 5 2 4 i Then, } word 0:7] wi ‘amazing (957) will give “anazing” (te letters starting from index 0 going up tl wite:3) wae, 7-1 ie, 6; from indices 0 to 6, both inclusive) 23] will give ama’ (letters from index 0 t0 3-1 ie, 0 to.2) , BY ER NIKHI 9; STRING MANIPULATION - 279 35 give ‘agit yordl 2 i “h she (letters from index 2 to 4 (ie, 5-1) ) d{-7 : -3] will give ‘amaz’ let aaa word[ te en indices ~7, 6, 5, 4 excluding yord[-5 + -1] will give ‘aziy. (letters from. indices 5, 4, 3,-2 excluding -1) from above examples, one thing must be clea to you : Tosee — | sng Sces © Inastring slice, the character at last index (the one { i , in actic is not included in the result. “one following colon ()) Bie ] | Ina tring slice, you give the slicing range in the form [sbegin-index> ;) a | Ii, however, you skip either of the begin-indey os last, Python will consider (ee) theimit ofthe string i, for missing begin-indes iy consider 0 (the first aR cote index) and for missing last value, it will consider length of the string Consider following examples to understand this ; word[ :7] will give ‘amazing’ (missing index before colon is taken as 0 (2er0) ) word{ :5] will give ‘amazi? (-do-) word[3:] will give ‘zing (missing index after colon is taken as 7 (the length of the string) ) word[S:] will give ‘ng (-do) ‘The string slice refers to a part of the string sfstartiend] that is the elements beginning at start and extending up to but not including end. Following figure (Fig. 9.1) shows some string slices : helloString[6:10] hellostring[6:] cree PLSD TTT WISE] noes (RTS dee [0123456789 10) index 012345678 9 10 t 7 + ° first lost first lost hellostringl3:-2] heldosering(:5] fj swces [Holi] ito] Jwle[r[i [a] tances [ae [i]o wloT] ia] we [0123456783 mn [DG 73456799 T iy t ¥ first lost fist lost Figure 9.1 string Sticing in Python. Interesting Inference Using the same string slicing technique, you will find that © for any index n, SI] + st] will give you original string & This works even for negative or out of bounds. 1. How are strings internally stored ? ‘2. For a string s storing ‘Goldy, what would s{o] and s{-1} return ? 3, The last character of a stri: index len(s) - 1. True / False ? 4. For strings, + means (1) :* means (2) ‘Suggest words for positions (1) and (2). gs is at Given that What is the output produced by following expressions ? {a) * The Knights who say, ” + 2 @) arsasetse \ (sift) i 6. What are membership operators? What do they basically do ? (on what principles, the strings are ! compared in Python ? 8. What will be the result of following i expressions ? (@) “Wow Python" [2] (8) "Strings are fun.” ij @ (@) “apple” > “pineapple” | () “pineapple” < "Peach" (9) “cad” in “ebracadabr: (h) “apple” in "Pineapple" I () "pine" in "Pineapple" | 9, what do you understand by sting i slices ? 410, Considering the same strings s1 and s2 | of question 5 above, evaluate the following expressions : | (@) s1[1:3] i (b) s2[2] + 52:2) (© st+s2f-1] bi (@) si:3] +s2[3:] i (e) s2{z-2] +s2[-1:] BY ER NIKHIL SI COMPUTER SCIENCE WITH Pytioy, Let us prove this with an example, Consider thesame iy % namely word storing ‘amazing’. yo» word{3:], word [:3] oar i, >>> word[ :3] +word[3:] ‘anazing [ens (llama, >>> word[ :-7], word [-7:] way toreverse a stig! * vamazing" >>> word[ :-7] +word[—7:] “amazing jrd (optional) index (say 1) in string slcg th element will be taken as part of look at following examples You can give a thi too. With that every 1 sliceeg., for word = ‘amazing’, >>> word [13622] Iwill take every 2nd character starting from index = Till nder <6 ‘man >> word [73-313] wil ake every Sd character ‘az! A mince nde 27 er 5 >>> word [: : -2] ‘gia’ very 2 character taken baclvants >>> word [: 2] “gnizama’ very character taken backwards Another interesting inference is = © Index out of bounds causes error with strings but slicing a string outside the bounds does not cause error. $= "Hello, Will cause eror because 5 is invalid print (s{5]) indes-out of bounds, for string "elit But if you give s= "Hello" One limits outside the Bounds - eng of Hell i and hs print (s[4: 8]) indees are 0-4) print (s[5 : 10]) Bo limits are outside the bounds the above will not give any error and print output as: 2 — = empty string ie, letter o followed by empty string in next line. The reason behind this is that when you use an index, you are accessing a constituent character of the string, thus the index must be valid and out of bounds index causes erroras there is no character to return from the given index. But slicing always returns a subsequence and empty sequence isa valid sequence. Thus when you slice a string outside the bounds, it still can return empty subsequence and hence Python gives no error and returns empty subsequence. ‘Truly amazing;). Isn’t it ?. s1fING MANIPULATION a rogram that prints the following pattern wi a i ithout using any nested loop ee a wae aeae | aeiee | Sample run of the program is as shown below : | string ie pattern # empty string ow for a inrange(S) : tHe } pattern += string see print (pattern) daa 45. STRING FUNCTIONS AND METHODS 5 | | python also offers many built-in functions and methods for string manipulation. You have already worked with one such method len( ) in earl one ier chapters. In this chapter, you will learn about many other built-in powerful string methods of Every string object that you create in Python is actually do anything specific for this ; manipulation methods that are by syntax: Python used for string manipulation. y an instance of String class (you need not Python does it for you ~ you know built-in). The string ing discussed below can be applied to string as per following In the following table we are referring to as string only (no angle brackets) but the meaning is intact i, you have to replace st | . () | fring with a legal string (ie, either a string literal or a string variable that holds a string value), Letus now have a look at some useful built-in string manipulation methods. Python's Buili-in String Manipulation Methods (ii copitlizet) Example | Retums a copy of the string with its first >>> string = it goes as - ringa ringa character capitalized. roses Example >>> [Link]() True >>> 1 love my India. capitalize() Tove my India t_ |shingfind|subp, stort, endj]) Returns the lowest index in the string where the substring sub is found within the slice Tange of start and end. Returns 1 if sub is not found, a >>> sub = ringa >> string. find(sub) B >>> string. find(sub, 15, 22) a >>> string. find(sub, 15, 25) 19 [Link]| ) Retums True if the characters in the string are alphanumeric (alphabets or numbers) and there is at least one character, False otherwise. 282 Example >>> string = "abc123" >>> string? = ‘nelle >>> string3 ='12345" >>> stringd = >>> string. isalnum() True >>> [Link]() True >>> [Link]() True >>> string¢.isalnun() False >>> [Link]{ ) Retums True if all characters in the string are alphabetic and there is at least one character, False otherwise. Example (considering the same string values as used in example of previous function -isalnum) >>> [Link]() False >>> [Link]() True >>> [Link]() False >>> [Link]() False [Link]{ ) Returns True if all the characters in the string are digits. There must be at least one character, otherwise it returns False. Example (considering the same string values as used in example of previous function - isalnum) 2> string. isdigit() False >>> string2. isdigit() False >>> [Link]() True >>> [Link]() False 14 ER NIKHIL SIR ‘COMPUTER SCIEI van y [Link]| ) Returns True if all cased characters string are lowercase. There must be at . cased character. It retums False othe Example >>> string = ‘hello’ >>> string2 = "THERE. >>> string3 = ‘Goldy >>> string. islower() True >>> string2. islower() False >>> [Link]() False [Link]( ) Returns True if there are only whitespac characters in the string. There must be at lea, one character. It returns False otherwise, Example >>> string="_" — # stores three spaces >>> string # an enpty string >>> [Link]() True >>> [Link]() False string isupper{ ) Tests whether all cased characters in the string are uppercase and requires that there be at least one cased character. Returns True if so and False otherwise. Example >>> string = "HELLO" >>> string? >>? strings >>> stringé = "U123" >>> strings = "123" >>> string. isupper() True >>? [Link]() False >>> [Link]() False >>> string4. isupper() True >>> strings. isupper() False # in uppercase # in lowercase BY ER NIKHI copter 9 STRING MANIPULATION. 283 [Link] ) Returns a copy of the string converted to | Returns a copy of the string converted to Jowercase. uppercase. Example (considering the same string values Example (considering the same string values as used in example of previous function - | as used in example of previous function - isupper) isupper) >>> string. lower() >>> string-upper(). ‘hello’ “HELLO >»> string? lower() >>> string2-upper() ‘there’ “THERE >>> [Link]() >>> [Link]() ‘goldy ‘cour’ >>> string’. lower() >>> stringé.upper() ‘u123 “u123 >>> strings. lower() >>> [Link]() 23 "123F Consider following program that applies some of the string manipulation functions that you have learnt so far. 9.4 Program that reads a line and prints its statistics like = a ‘Number of uppercase letters : Number of lowercase letters: Number of alphabets : ‘Number of digits: Line = input( "Enter a line :") Jowercount = uppercount = @ digitcount = alphacount = @ for ain line Sample run of the program is : if [Link]() : ; | Towercounexea | enter a Tine : Hello 123, zippy zippy zap | Nunber of uppercase letters i 7 Nunber of lowercase letters : 11 uppercount += 2. | Number of alphabets : 18 elif [Link]() : Nunber of digits : 3 digitcount +21 if [Link]() : alphacount += 1 elif [Link]() : print (“Number of uppercase letters :", uppercount) print (“Number of lowercase letters :", lowercount) print ("Number of alphabets :", alphacount) print ("Number of digits :", digitcount) 284 im that reads a line and a substring. It shoul. 9.5 Progra’ given substring in the line rogram Line = input( "Enter line :") sub = input ("Enter substring :" ) Jength = len(1ine) Jensub = Len(sub) start = count =@ end = length while True : pos = [Link](sub, start, end) if pos !=-1: count start = pos + lensub else: break if start >= length : break print ("No. of occurrences of", sub, ':', count) ‘Sample runs of above program is : Enter Tine : jingle be11s jingle bells jingle all the way Enter substring : jingle No. of occurrences of jingle : 3 RESTART Enter line : jingle bells jingle bells jingle al1 the way Enter substring : bells No. of occurrences of bells : 2 1. What is the role of these functions ? (0 ssalpha() (i) isalnum( ) (ip iso) (iv Ssspace() Sp 2 Name the case related string mani- ee polation functions. 3. How is islower( ) function different from lower( ) function ? 4. Whats the utility of find{ ) function ? 5. How is capitalize ) function different from upper( ) function ? STRING MANIPULATION pice This ‘Progress in Python’ session works on the objective of practicing String manipulation operators and functions. computer sciehte Stites I Id then display the number of occurren 8 of, Progress In Python 9.1 * BY ER NIKHI chopter 9: STRING MANIPULATION 285 Let US REVISE Python strings Pere in memory by storing {individual characters in contiguous memory locations The memory locations of string characters are given indexes or indic i ‘ The index (also called subscript sometimes) is the . In Python, ind backward direct For strings, eee! begin 0 onwards in the forward ion. This is called two-way indexing * means concatenation, * means replication, @ for ASCH or Unicode. Place in dictionary order by applying character-by-character comparison rules The ord) function returns the ASCII value of given character, & The string slice refers to.a part ofthe string s[startzend) is the e ining at start and extending up to but not tend] is the element begi i sr ient beginning at start a 9. She sing sce with ste sitar: end nf isthe element beginning at strtand extending up o but not including end, taking every nth character, ‘Python also provides some built-in string manipulation methods like: capitalize) find) isalnum(),isalphat ), Isdigit(), tslower( ),isupper( ), lower( ), uppert ) etc. Solved Problems cecum 1, What is a string slice ? How is it useful ? Solution. A sub-part or a slice of a string, say s, can be obtained using s In :ml where n and m are integers. Python returns all the characters at indices m, n+1, n+2...m-1 eg, “Well done‘ [1 : 4] will give ‘ell' Figure out the problem with following code fragment. Correct the code and then print the output. 1. i=" must’ 2. s2=" try’ 3. n= 10 4, 223 5S. print (si +s2) 6. print (s2 * n2) 7. print (si +n1) 8. print (s2 * s1) Solution. The problem is with lines 7 and 8. © Line 7 - print s1 + n1 will cause error because s1 being a string cannot be concatenated with a number ni. This problem can be solved either by changing the operator or operand eg, al the following statements will work : (a) print (si * n1) (®) print (s1 + str(n1)) (©) print (s1 + s2) Pi BY ER NIKHIL Sil COMPUTER SCIENCE WITH Pyiioy, 286 ; Line 8 ~ print (s2 * s1) will cause error because two strings cannot be used for "lig f The corrected statement will be: print (52 +51) ae ‘on (b) If we replace the Line 7 with its suggested solution (6), the output will be: must try try try try must 10 try must 3. Consider the following code : string = input("Enter a string :") count = 3 string = string[: elif string[-1] string = string [: 2] i else : count += 2 } break print (string) print (count) | What will be the output produced, if the input is: (i) aabbcc (ii) anccbb (iii) abce ? Solution. (@) bbee | (b) ce (c) ce 4 4 4 4, Consider the following code : Inp = input( "Please enter a string :" ) while len(Inp) <= 4 : if Inp[-1] =='2 : #eondition 1 Inp = Inp [@: 3] +'¢ elif’ a’ in Inp : Heondition 2 Inp = Inp[@] + ‘bb’ elif not int(Inp[o]. Inp ='I' + Inp[1 :] +'2 else : np = Inp +'* print (Inp) What will be the output produced if the input is (i) 1bzz, (ii)" 1a" (iii)' abe" (io)" Oxy (v)' xyz"? Solution. ; (i) Lbzcx (ii) Tobe condition 3 BY ER Nik chopter 9: STRING MANIPULATION 287 if) endless loop because endlessly “wil always remain at index 0 and condition 3 willbe repeated (io) 1xyex (0) Raises an error as Inplo} cannot be conv, 5, Write a program that takes a string with muni ital forms anew string out of i, 8 tH Mp words and then capitalizes the firs letter of ech word and Solution. string = input( “Enter erted to int, | a string 2") Length = len(string) ae ; end = length | string2 ="" Henpty string | while a < length : | ifasse: string2 += string[@].upper() ater elif (string[a] =="* and stringfata] 1=* string? #= stringla] string? += string[a+a] .upper() ats2 else: string? += stringla] atea | print (“Original string :", string) | print (“Capitalized words String", string2) 6. Write a programs that reads a string and checks whether it is a palindrome string or not, Solution. string = input( "Enter a string :" ) length = len(string) mid = Lengtih/2 rev = -1 for a in range(mid) : if string[a] == string[rev] : ated rev -=1 else : print (string, “is not a palindrome": break else: print (string, "is a palindrome") 7. Write a program that reads a string and displays the longest substring of the given string having just the consonants. Solution. string = input( “Enter a string length = len(string) compurer sClENCE iti Ki|L 288 maxlength = mmaxsub ="* sub ="" lensub = @ for a in range(length): if string[a] in ‘aeiot if Jensub > maxlength ? rnaxsub = sub maxlength = lensub sub ="* Jensub = @ # empty string # empty string uf on stringfa] in 'AEZOU" + else: sub 4= stringla] Lensub = len(sub) ated ia print ("Maximum Length consonant substring 35 ¢ print (“with" , maxlength, "characters") string and then printsa string that capitalizes every oth “ , maxsub, end = ' ') 8. Writea program that reads her letter in the string eg, passion becomes pAsSiOn. Solution. string = input( "Enter a string’:" ) Jength = len(string) print (“Original string :", string) string2 # empty string for a in range(®, length, 2) = string? += string[a] if a < (length-1) : string? += string[a + 2)-upper() print ("Alternatively capitalized string » string2) ©. Write a program that reads email-id of a person in the form of a string and ensures that it belongs to domain [Link]. (Assumption : No invalid characters are there in email-id) Solution. email = input( "Enter your email id :" ) donain = (@[Link]' edo = 1en(donain) # edo — length of domain Jena = 1en(enail) # Lema — length of email sub = email[1ema-ledo :] if sub == domain if Lledo != lena : print (“It is valid email id") else : print ("This is invalid email id - contains just the domain nane.") else: Print (“This enail-id is either not valid or belongs to sone other domain.”) BY ER NIKH{ apter 9 : STRING MANIPULATION, cos 289 GLOSSARY eal only Avoriable or value used to select @ member characler from a string, Pecitied by a range of indices, ‘subscript — Index. Trersl__Weoting trough o sequence such oso sting, member by member, Assignments neu Type A: Short Answer Questions/Conceptual Questions For Solutions for Selacted Questions 1. Write a Python script that tr iipartaas ; hoc ince Isr ease ere AE rns 2 Out ofthe following operators, which ones can be used with stings ? Fn te th % > €>, in, notin 3. What is the result of following statement, if the input is ‘Fun’ ? | print ( input(" ... ") + "tial" + "Ooty" #3) 4. Which of the following is not a Python legal string operation ? (@) ‘abe + ‘abe (0) ‘abe +3. (0) ‘abe +3 (@) ‘abc’.lower() 5. Can you say strings are character lists ? Why ? Why not ? 6. Given a string § ="CARPE DIEM". Ifn is length/2 (length is the length of the given string), then what I would following return ? } (a) Sn} () Sir (Sfn:n] @Slsn) (Sin: length - 1] ’. From the string S = "CARPE DIEM", which ranges return "DIE" and "CAR" 2 8. What would following expression return ? (@) "Hello World" upper( ).lower( ) (®) "Hello World” Jower( ).upper( ) (0) "Hello World" find( "Wor', 1, 6) (@) "Hello World” find( "Wor") | ("Hello World” find( “wor’) () "Hello World” isalpha( ) | () “Hello World” isatnum( ) (i) "1234 isdigit( ) | () "123FGH" isdigit( ) 9. Which functions would you choose to use to remove leading and trailing white spaces from a given string ? | 10. Try to find out if for any case, the string functions isalnum( ) and isalpha( ) retum the same result. 11. Suggest appropriate functions for the following tasks : () To check whether the string contains digits (i) To find for the occurrence a string within another string (ii) To convert the first letter of a string to upper case | (io) to capitalize all the letters of the string | (©) to check whether all letters of the string are in capital letters (i) to remove from right of a string all string-combinations from a given set of letters (ei) to remove all white spaces from the beginning of a string BY ER NIKHIL SIR COMPUTER SCIENCE WITH Prtyoy, 290 . Type B : Application Based Questions . What is the result of the following expressions 2 " (as ='9123456789 print (13], ")"» S(@2 31. "=", sia: 5) print (s{:3]."~") 50341) "> "s s[3:109)) print (s[20:], s[2:2], s[1:2]) (@) print (* s ='987654321' print (s[-2], s[-3]) print (s[-3:], s[:-3]) print (s[-100:-3], s[-100:3]) (b) text = "Test. \nNext Line." © print (text) (0 print Cone’, ‘ Two" * 2) print (‘One '+'Two' * 2) print (1en('0123456789)) 2. What will be the output produced by following code fragments ? (@ y= str(a23) () x= "hello" +\ (9 x= "hello world” “hello” * 3 to Python" + \ print (x[:2], x{:-2], x{-2:) print (x, y) “world” print (x[6], x[2:4]) "hello" + "world" for char in x t print (x[2:-3], x{-4:-2]) fen(x) y= char print (y, x) print (y,':', end=" 3. Carefully go through the code given below and answer the questions based on it : theStr =" This is a test" nputStr = input(" Enter integer inputint = int(inputStr) testStr = thestr while inputlnt > testStr = testStr[1:-1] inputint = inputInt - 1 testBool ="t' in teststr print (theStr) # Line 1 print (teststr) # Line 2 print (inputInt) # Line 3 print (testB0ol) # Line 4 () Given the input integer 3, what output is produced by Line 1? (a) This is atest (b) This isa —_(¢) isa test (@) isa) None of these (i Given the input integer 3, what output is produced by Line 2 ? (@ Thisisatest (b)sisat (isa test (d) isa (e) None of these (iii) Given the input integer 2, what output is produced by Line 3? @o 1 @2 @3 (© None of these (io) Given the input integer 2, what output is produced by Line 4? (@) False (b) True (Oo (a1 (©) None of these BY ER NIKHI chopter 9 : STRING MANIPULATION 291 4, Carefully go through the code gi r testStr = "abederghie oe” Below and answer the questions based on it: AnputStr = input ("Enter integer inputInt = int (inputstry count = 2 newStr ="* while count <= inputint : newStr = newstr + teststr[@ : tesestr= testsertzy SAME) count = count +1 print (newstr) # Line 2 print (teststr) # Line 3 print (count) # Line 4 print (inputint) # Line 5 (Given the input integer 4, what output is produced by Line 2? (@) abedefg (0) aabbccddeetigg (¢ abedeefgh (i) ghi_(@) None ofthese Gi) Given the input integer 4, what output is produced by Line 3 ? (@) abedelg (0) aabbeeddeetigg (©) abedeefgh _() ghi (©) None of these (Gi) Given the input integer 3, what output is produced by Line 4 ? (@ oO @)1 @2 (@) 3 (@) None of these (2) Given the input integer 3, what output is produced by Line 5 ? (0 @1 2 (3 None of these (©) Which statement is equivalent to the statement found in Line 1? (@) teststr = teststr[2:0] © teststr = teststr[2:-2) (© teststr = teststr[2:-2] (@ teststr = teststr —2 (©) None of these 5. Carefully go through the code given below and answer the questions based on it : 2") inputStr = input(" Give me a strin bigint = @ littleint = @ otherInt = @ for ele in inputstr: if ele >='a' and ele <='nt: Littlelnt = littlelnt +4 elif ele >‘m' and ele coz" bigint = bigint +1 else: otherInt = otherInt +1 print (biglnt) # Line 2 print (1ittlelnt) # Line 3 print (otherInt) # Line 4 print (inputstr. isdigit()) # Line 5 # Line 1 (Given the input abed what output is produced by Line 2? @o OI 2 @3 ©@4 compurer scleNce nt Ss S! 292 bine 3? . : ‘ is produced by Line © * (i Given the input Hi inal oes = Produ None of these @o i } 7 (iif) Given the input Hi Mom what a . produc Nore of het 2 @mo @1 © ) ne? Given the input 1+2 =3 what output is produced i sr ian 0 © 1 @True (a) False o one ae (o) Give the input Hi Mom, what changes result from mo fying if'ele >= ‘a’ and ele <=‘m" to the expression ifele >='a and ele <'nt'? ; sabe tage 1d be larger _(¢) littleInt woul ger (a) Nochange (0) otherint woul hae (@ bigint would be larger (None of a «6 Carefully go through the code given below and answer the questions Das on it : iniStr = input(" Enter string of digits: $naStr = input Enter string of digits: (@) if len(inistr)>len(in2str): small = in2str large = instr else: small = inistr large = in2str newstr ="* for elenent in small: result = int(elenent) + int(large[®]) newstr = newStr + str(result) large = large(1:] print (len(newstr) # Line 1 print (newstr) # Line 2 print (large) # Line 3 print (small) # Line 4 (0 Given a first input of 12345 and a second input of 246, what result is produced by Line 1? @1 ©3 ©5 0 None of these (i) Given a first input of 12345 and a second input of 246, what result is produced by Line 2? (@) 369 (246 (234 (@) 345 (€) None of these (iii) Given a first input of 123 and a second input of 4567, what result is produced by Line 3? @3 (7 ~—©12_—@4S_—_(&) None of these (iv) Given a first input of 123 and a second input of 4567, what result is produced by Line 4? @ 13° 4567 (7 3 (@) None of these 7. Find the output if the input string is ‘Test’. @ : input ("Enter String :") () $= input("Enter string : R=" for chins: for ch ins : RS = ; 'S = ch + RS RS =ch+24RS print(S + RS) print(RS +S) BY ER NIKH| 9: STRING MANIPULATION cooptet ° pa 3 Find the errors. Find the line numbers caus (@ 1. S="PURA vipa" sing errors, 2. print(S[9] + s[9 : 157) ® = See } . 110] +S[10 : S[29] + s{-10] "PURA VIDA" s*2 (1, S ="PURA VIDA" 3. S2=S1[-19] + saf-20) 2, SL=S[: 5] 4, $3 =S1[-19 :] 3. S2=S[5 2] 4, S3=51*52 5. S4=s2 43" Type C : Programming Practice/Knowledge based Questions 1, Write a program that prompts for a phone number of 10 dij it igits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input Display if the phone number entered is valid format or not and display i is vali P not and display if is valid or not (ie, contains just the digits and dash at specific places, ie plore ine eal 2. Write a program that : 4 prompt the user for a string extract all the digits from the string, A If there are digits : 4 sum the collected digits together 4 print out : * the original string «the digits © the sum of the digits 4 If there are no digits: 4 print the original string and a message “has no digits” Sample 4 given the input : abcl23 prints abcl23 has the digits 123 which sum to 6 | & given the input : abed prints abed has no digits 3. Write a program that should prompt the user to type some sentence(s) followed by “enter”. It should then print the original sentence(s) and the following statistics relating to the sentence(s) : 4 Number of words 4 Number of characters (including white-space and punctuation) 4 Percentage of characters that are alpha numeric Hints 4 Assume any consecutive sequence of non-blank characters is a word. 4, Write a Python program as per specifications given below : 4 Repeatedly prompt for a sentence (string) or for “d to quit. 4 Upon input of a sentence s, print the string produced from s by converting each lower case letter to upper case and each upper case letter to lower case. 4 Alll other characters are left unchanged. BY ER NIKHIL SIR i COMPUTER SCIENCE WITH Prrigy " La 294 For example, . RESTART Please enter a sentence, ‘tHIS IS THE bOwB! Please enter a sentence, or'q' to WHAT?S UP dOC 27? Please enter a sentence, or 5, Write a program that does the following 14 takes two inputs : the first, an integer and the s 4s from the input string extract all the digits, in the order # set the extracted digits to 0 ted from the string together as integers quit : This is the Bonb! or'¢ to quit : What’s up Doc ??? tg to quit: .econd, a string hey occurred, from the string. 4 if no digits occur, 4 add the integer input and the digits extr 4 print a string of the form = ““integer_input + string digits = sum” act For example For inputs 12, * abci23'—>' 12 +123 = 135" For inputs 20, * aSb6c7' > 20 + 567 = 587" For inputs 108, ‘ hi mon’ >" 100 + @ = 100° rings ? Write a program that takes two strings from the x this format : i 6. On what principles does Python compare two st user and displays the smaller string in single line and the larger string as pe i ast letter Jast letter j 2nd letter 2nd last letter | ard letter 3rd last letter i For example, th if the two strings entered are Python and PANDA then the output ‘of the program should be : i PANDA ! P n y ° Write a program to convert a given number into equivalent Roman number (store its value asa sting) You can use following guidelines to develop solution for it : From the given number, pick successive digits, using %10 and /10 to gather the digits from right oe. 44. The rules for Roman Numerals involve using four pairs of symbols for ones and five, tens and fies hundreds and five hundreds. An additional symbol for thousands covers all the relevant bases. ii 4 When a number is followed by the same or smaller number, it means addition. “II” is two 18-2 CVI" is 5+1=6. ‘A When one number is followed by a larger number, it means subtraction. L before 10-9." isn't allowed, this would be "VIII". For numbers from 1 to 9, the symbols are "I" and " coding works like this. "I", “II, "mI, “IV, "V’ ovr," 4 The same rules work for numbers from 10 to 90, using "X" and "L", For numb i using the sumbols °C” and "D". For numbers between 1000 and 4000, using " i Here are some examples. 1994 = MCMXCIV, 1956 = MCMLVI, 3888= MMMDCCCLXXXVI —

You might also like