Page 1 :
5.1, , , , String, Manipulation, , eB ees, , tn Ws Chapter, , 5.1 Introduction, , 5.2 Traversing a String, , 5.3 String Operators, , 5.4 String Slices, , 5.5 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, , ings like — ing i i has 0, i i Iso learnt things like - an empty string is a string that, Pe a eee and that Python strings are immutable. You, , characters (i.e., it is just a pair of quotation marks), , have used strings in earlier chapters to store text type of data. ., ence of characters, where each character has a unique, , i fu : ., You crow rae aa one a ona begin from 0 to (length - 1) in forward direction and, Position-id/index., , a =, th in backward direction. . . . |, , him 2, ~. er ma going to learn about many more string manipulation techniques offered, is chapter, you ar, , by Python like operators, methods ete.
Page 2 :
i046 COMPUTER SCIENCE yiityy y, , ther, , 5.2 TRAVERSING A STRING, , You know that individual characters of a string are accessible through the UNIQUE indey oy, character. Using the indexes, you can traverse a string character by character ‘J; vers) ‘, to iterating through the elements of a string, one character at a time. You, ha, traversed through strings, though unknowingly, when we talked about Sequences alony ,, , for loops. To traverse through a string, you can write a loop like : _, , name = "superb", ————— This loop will traverse Cur, , , , for ch inname : through string name charac- iy, ‘haracter., rint (ch, '!, end='' lee, pi (ch, , ) Traversing refers to tersing, . *. through th RENTS of a «>, The above code will print : ough the elements of 3 5 4, one character at a+ me, S-U-p-e-r-b, The information that you have learnt till now is sufficient to create wonderful Programs, , manipulate strings. Consider the following programs that use the Python string indexing, display strings in multiple ways. :, 5.1 Program to read a string and display it in reverse order - display one chara, Do not create a reverse string, just display in reverse order., rogram, string1 = input( "Enter a string :"), print ("The", string1, "in reverse order is:"), , length = len(string1) ., Since the range() excludes the number, for a in range(-1, (-length -1), -1): mentioned as upper limit, we have, , print (stringi[a] ) taken care of that by increasing the, limit accordingly., , Sample run of above program is :, , Enter a string : python, The python in reverse order is:, , o<xdsros, , 5.2 Program to read a string and display it in the form :, , — first character last character, , second character second last character, , For example, string “try” should print as :, ty, ror, , y t
Page 3 :
chooter 5 = STRING MANIPULATION, , . 185, string1 = input,, , "Enter a, length = len(string1) Str, i=@, , forain range(-1, ( i, , ~length-1) y Pe,, , i r 271); When you give a negative index,, print (stringitiy, "\t"> stri Python adds length of string to, itt , mngi[a]) get its forward index e.g., for a, S-lettered string 5, S[-1] will, give $[-1 +5] i.e., $ [4] letter ;, for S[-5], it will give you, , ing :"), , Sample run of above Program is :, , Enter a string : python S[-5+5]ie, $ [0], p n, y °, t h, h t, ° y, n p, , 5.3 STRING OPERATORS, , In this section, you'll be learning to work with various, , . . 7 operators that can be used to manipulate, strings in multiple ways. We’, , : v ‘Il be talking about basic operators + and *, membership operators, in and not in and comparison operators (all relational operators) for strings., , 5.3.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 immutable i.e., un-modifiable. Thus every time, you perform something on a string that changes it, Python will internally create a new string, rather than modifying the old string in place., , String Concatenation Operator +, The + operator creates a new string by joining the two operand strings, e.g.,, , "tea" + "pot", will result into Two input sirings joined (concatenated) fo, , form a new string, ‘teapot’, , Consider some more examples :, will result into, , Expression ng, 4d!, ‘a’, #a" fe "Q" :, *123abc, , "423' + ‘abc’
Page 4 :
eal, = COMPUTER SCIENCE WITH PYTHON,, , Let us see how concatenation takes place internally. Python creates 4 ee es ops, by storing the individual characters of first string operand follow y the indivig, characters of second string operand. (see below), , clelal « [plalel =, A, , String operands ===:, , , , , , New string created by, joining String operands, , , , , , Original strings are not modified as strings are immutable ; new strings can be crea, , existing strings cannot be modified., , Caution!, , Another important thing that you need to know about + operator is that this operator can y,, with numbers and strings separately for addition and concatenation respectively, but in the sa,, expression, you cannot combine numbers and strings as operands with a + operat, , For example,, , 2+3=5 # addition - VALID, ‘2+ 23' # concatenation - VALID, , , , But the expression, ‘243, is invalid. It will produce an error like :, , >>>'24+3 Crrrae, , The + operator has to have bot, operands of the same ty?, either of number types ('0, , Traceback (most recent call last):, File "<pyshell#2>", line 1, in <module>, , ine addition) or of string types (fo, TypeError: cannot concatenate'str' and ‘int’ objects multiplication). It cannot wor, with one operand as string 2", , Thus we can summarize + operator as follows : one as a number., , ‘Table 5.1 Working of Python + operator, , , , , , , , , , , , Operands’ data type Operation performed by + Example ], | numbers addition 94+9=18, | string concatenation "9" 4. "g" = "9g" |, , , , String Replication Operator *, , The * operator when used with numbers (i.e, when both operands are numbers),, 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 4 number, |, number * string or string * number., , it perfor?
Page 5 :
ger 5:1 STRING MANIPULATION oF, ¢ 187, , Where string operand tells the stri, , times, it is to be repeated; Python to be replicated and number operand tells the number of, , , , string operand, ll create a new string that is a number of repetitions of the, For example,, 3%!" Coe, For replication operator *,, will return Tn . Python creates a new string that, iput strings i g tha, 'go!go!go!" Ay of times to jislmsen number . a -— of repetitions of the, input string., Consider some more examples :, Expression will result into, “abet &, abe" * 2 “abcabc", 5 *"@" “aaaaa, gat ag Wee ce ecm, qe * 2 oa" “—, , Cautions, , 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 strivigs as both the operands with a*, operator., , For example,, , 2*3=6 # multiplication - VALID, "2" *3 ="222" # replication - VALID, But the expression ia eae, apne eit The * operator has to either have, both operands of the number, is invalid. It will produce an error like : types (for multiplication) or one, String type and one number type, >>> mgm e gt (for replication). It cannot work, with both operands of string, Traceback (most recent call last): types., File “<pyshell#@>", Line 1, in <module>, ea, , TypeError: can’t multiply sequence by non-int of type'str’, , Thus we can summarize + operator as follows :, , ‘Table 5.2. Working of Python * operator, , , , , , , , [ Operands’ data type, , Rumbers __——, , string, number, , , , | number , string