You are on page 1of 33
6.1 INTRODUCTION afer 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 ata 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. The same concept used for a necklace made up of beads holds true for strings in computer. When you see a sentence, you understand that it is made up of individual characters that are strung together by the programming language you use. The language creates a structure that holds individual characters together, So, the language, and not the computer, knows that so many alphabets or numbers in a row (each number being represented as a character) make a string °ra sentence, In Python too, like in real life, we deal with strings Now the question arises— > Where have we seen strings before? Recall the simple programs that we have discussed in the previous chapters. ‘\ program to display a “Hello mes the Python code for this: se" to the user that combines with his/her nam AME, Cy Ong La prog. sie py - Cyuserspreeti/AppOata/tocal/Programs.. ~ © KEI 4 fie 6 fost fan Options Nd hp print ("Enter your name: ") 4 ame = input () print (*Hello"+nana) Fie {8 Shell Debug Optane Window Help python 3.6.5 (v3.6.5:£59¢0932b4, Mar 29 2018,-1- 6207346) (MSC v.1900 32 bit (Intel)} on wings Type "copyright", “credits” or "license()" for more information. >>> — RESTART: C:/Users/preet /AppData/Local/Progran 9/Bython/Python36-32/prog_strl.py Enter your name: Rinku HelloRinku >>> In the above example, the sentence we have typed in print() method, i, Enter your name) complete sentence or a string, Even though you see a sentence, Python sees a Specific numbey of characters. Similarly, the output message displayed as “HelloRinku’ is again a string. Sol can say a string more or less behaves like a variable holding characters or alphabets inside double quotes. i 6.2 WHAT ARE STRINGS In Python, a consecutive sequence of characters, which are enclosed or surrounded by single () or double (“") quotes, is known as a string. This sequence of UNICODE characters nay include a letter, a number, special character, whitespace or a backslash, Astring may be specified by placing the member characters of the sequence within quotes (single, double or triple). Python treats single quotes the same as double quotes, Python String py_string = "Python Strings" Triple quotes are typically used for strings that span multiple lines. For example, Fruit jango Apple Grapes’ In the above example, we have a string with the names of fruits and space in betel viz. Mango#Apple#Grapes (where # indicates a space) enclosed inside single quotes’ + Y representing a string value assigned to the variable ‘Fruits’, Like other integer variables, string are also declared in the same manner using ‘=' operator. 6.3 CREATING STRINGS Strings are among the most popular data types in Python, We can create them by a enclosing characters in quotes (single, double or triple). Python treats single quotes the 4 as double quotes. Sometimes, triple quotes can be used in Python but they are gene to represent multiline strings and doc strings. An empty string is a string that has 0 ¢ Creating strings is as simple as assigning a value to a variable. | | le, ean " ello world’ & rogramming" f 1 python PI s Window Hep 59c0932b4, Mar 28 2018, 1 7 C v.1900 32 bit (Intel)] on win32 copyright", “credits” or e re information. go» az "Good Morning" ma ‘good Horning’ "license ()" for = yy» a= ‘Good Horning’ ext can be enclosed within single cr double quotes, both are treated as stings. ya ‘good Horning’ support a character type; python does no! considered a substring. "py ‘care all strings of length one. for example, ‘a, Double quotes and single ‘To insert them in a string, indicate the special nature of the chara quotes are you have to escape them (i. cter). For example, Fie Edt Shell Debug Options Window Help python 3.6.5 (v3.6.5 6:07:46) [MSC v.1900 32 Type “copyright”, more information. yop ae rite article on \'AI\" briefly " doo priate} ‘Write azticle on salt bristly >>> c="this is Meera\'s pen" << Fig, 6.2: Creating a String gle or double quotes; these are trea part of the Python language; they are spe £59c0932b4, Mar 28 2018, pit (Intel)] on win32 credits" or >>> print (c) This is Meera's pen both represent a string. _ ted as strings of length one, thus, also cial characters. e, with a \ character in front of them to 1 "license ()" for We can insert double quotes and) single quotes inside a string by using backslash (\) character. mp: pro gelio World" st ypython Programming 2° 3 python 3.6.5 (3.6.5: £59c0s3apq 6:07:46) (usc V.1900 32 bit Cintenny =n ta Type "copyright", "credits" says, more information, >>> a= "Good Morning" >a "Good Morning’ a4 8, 1 32 or “license()" for Text can be enclosed within single of double quotes, both are treated as strings >>> a ‘Good Horning! ma "Good Yorning! python does not support a character type; considered a substring. For example, ‘a’, ‘bi, ‘c’ are all strings of length one. Double quotes and single quotes are Part of the Python lan, To insert them in a string, you have to esca indicate the special nature of the character) For example, File Edit Shell Debug Options Window Help Python 3.6.5 (v3.6. 5:£59c0932b4, Mar 28 2018, 1 * 6:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license Q"™ for more information. 2 a Nittite article on \"AI\" briefly " >> priat la} Write article on *AI* bristly >>> c= i "Ss pen" ‘We can insert double quotes and Stier SSS tate cuotes ide s snmp ee using backslash (\) character, This is Meera's pen these are treated as Strings of length one, thus, also guage; they are special characters. pe them (ie, with a \ character in front of them to > Empty String An empty string is a string without any characters inside, having length zero lg Python 3.6 File Edit Shel! Debug Options Window Help RESTART: Shell >>> stre"" >>> print (str) >>> strat! >>> print (str) As is evident from the above example, string str does not hold any value, i. string. Therefore, when we print an empty string, a blank space gets displayed in the nex If a command is long, then it can be shifted to the next line by typing ‘\, but it shor result in the same line. For example, File_Edt Shell Debug Options Window Help Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, * 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or “license()" for more information. >>> ae Here ts a Line \ split in two lines® >>> print (a) Here ig a line split in two lines >>> If you wish to display the output on the next line, then the use of escape sequence becomes mandatory. For example, File Edt Shel Oebug Options Window Hep E Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, * 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. | >>> c="we are Indians \n and ve love our country" >>> print (c) we are Indians and ve love our country FP | | | n also use escape sequence (\t) to tabulate the output. ut at example, yea File_Edt Shell Debug Options “Window , +6.. a ieorsa6) tase SceeteBeO8REDT, Mar 28 2018, 2 bit (Intel)) on win3 Type “copyright”, “credits r more information or "License()" to >» als"iane\t class \t section >> al*RIA\E Mt bY >> print (at jae class section >> print a2) am po > Multiline Strings Multiline strings are represented using triple quotes ("“"") or even single or double quotes. Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [MS * © v.1900 32 bit (Intel)} on win32 Type "copyright", "credits" or "license()" for more informa J multiline string | example''" J>>> print (s) this isa [multiline string example dep gn ttt we aze studenss Jwe study computer science Jprogreming language 42 python’ >> print(s) we are students we study computer science [progranning language 18 python >> sein Eas sera c sequence ingle double or tiple). mtuanaienc ae 6.4 TRAVERSING A STRING ; Traversing a string means accessing all the elements of the string one the subscript or index value. after the other by using dA tach character ina string is located in diferent slots (like Lacks) 85 Sewn Ini ach chara For example, Consider a string as: "hello world!" str hlefti to wlofrjt{di! 0123456789101 b Fig, 6.3: Character Representation in string i i at 0 and must be an j ach character in a string has an index value. Indexing starts phd Individual elements/slots can be accessed by typing index value inside square [ ] brackets shown in the output window given below. Tle_E6t Shel Debug Options Window Hele more informatior >>> varl = "Hello World” >>> print (varl(0]) X >>> print (varl (4)) ° >>> print (varl{-8]) 1 >o> print (varl[-6]) >>> print (vari[-81) " >> We can't use float or other types for index as this will result in TypeError: Trying to access character out of index range will raise an IndexError. We can start index value either from the left or from the right. Left index starts from 0 an right-side index starts from -1. String A ep ty [ta foyn Positive Index Ce: Negative Index ~« [3s [43 [2 [a Here, each element or character of the string is associated with an index and can be access by its index value. To access any subscript of a string, we use the square brackets along wit the index. For example, varl ='Hello World!" vart Hy el eal co Wofoo ford [al Positive Index oe Pasa ls | 6] rua] 9 Negative Index -2|-1|-10[ -9 |) afoetst als ating enrouelt StTNg Using for oop ring can be accessed se er of the race aque cl erating - tha Sie an path la erating ver I results tn dispay Tally using for loop, ‘this is done using ng the clemei f the elements of a string, one character str ‘computer Science! for i in strt print (i) we code, the loop starts from the first character nthe abo ig ‘str’ and automatically ends when the last ofthe strin character is accessed. b) erating through string (String Traversal) using while loop ring traversal. Each element of the string is accessed which can be determined Like for, while loop can also be used for ‘one and while loop iterates till the end of the inputted string, Here while loop runs till the condition index < len(str) is ‘True, where index varies from Sto len(stri)-1. one by using standard library function, len().function. Fle Eat Format Run Options Wind >>> 1 #String traversal using while loop . RESTART?) strl = "Python Programming!" essl.py | index = 0 P | #len() function to get length of string Ny while index < len(strl): t | print (str1 [index] ,end = *\n") n | index += 1 ° cindex e200 tn | es | | r | ° | g | r | a | Ly | n I i | n | | : | i t Practical mpte Write a Program to count the number of occurrences of Complementing Stving traversal) |trunctton to count ifstring jstr = input ("Enter a string: ") ch = Anput ("Enter the chatacter to be searched: *) count = 0 [for character in stry > if character == ch: count + 1 (print ("wunber of times character", ch, “occurs in the string \ count) Mentatlon-1 @ character in an inputteg str ing the number of tines @ character” decues ti, aC /Users/preeti /AppData/Local/Programs /Python nm Enter a string: python is eas: Y and Interactive Enter the character to be searched: e Practical Implementation-2 Write a program to input a strin; creating a new string, |tProgram to display string In reverse order str = input ("Enter a string: ") for 4 in range (-1,-1en(str)-1,-1): print (str[i),end=" ") SS RESTART: C:/Users, ott -Py Enter a string: Reversing string mirts gnisrever /preeti /AppData 6.5 SPECIAL STRING OPERATORS String can be manipulated using o} perators like concatenate (+), repetition ( operator like in and not in, *) and membershig (GSD sinstanos Gere Setnsmserya (Teer) suing + suing orenons GEM se i Common String Operations ea Stel Debug Options Window Help a fi enon 3-6-5 (93 6-8: £59¢0932b4, ar 95 0 32 bit (Intel)} on win32 “8 2018, 16307346) ope copyright", “credits ( en BC val Conse ()" for more 4 vp eo Kora! hformatiion, Jyello World" > ca"Good " — ” Morning 2 print (c) Good Morning —_—_———— to add an integer value toa string, it will ge ed by Python interpreter in case of incomps wet generat nerate an error, ie atible data types as shown below: ue tat_Sbel Debug Opt Window Hep python 3.6.5 (v3.6.5:£59c0932bi, Mar 20 D0I% 900 32 bit (Intel)} on win32 a type "copyright", "credits" or "License()" >>> 2 +"book" Traceback (most recent call last): File "", line 1, in 2 +"book" TypeError: unsupported operand type(s) for +: ‘int’ and ‘str! 16:07:46) (MSC v. for more information However, you can use concatenation operator ‘+’ with numbers and strings separately for performing addition and concatenation operation respectively. For example, 64+3=9 #addition ‘6’ + ‘3’ = 63’ #concatenation But the expression— ‘6! +3 shall generate an error as shown in the above output window. 6.5.2 Replicating Strings The * operator creates a new string by repeating multiple copies of the same string. ‘Shell Debug Options Window Help >>> 3*'Hello ' ‘Hello Hello Hello ' >>> 2682" 129" For replication operator *, Python creates a new string that is a number of repetitions of the put string, ‘Typekirror will be | or example, [>>> stm "python' >>> str * 3 fusing variable str ‘PythonPythonpython' >>> gh fist Traceback (most recent call last): File "", line 1, in tgy ae t5t TypeError: can't multiply sequen ee A: Th | * operator has to either | av ‘operands ult UlGreiseripsGs done num Gr (for replication), operands ofstring types, = * types (for perp It cannot wor ‘The last statement shall result in an error because strin; to be an integer value. gs can't be multiplied; one operand h 6.5.3 Membership Operators Python offers two membership operators for checkin 1g whether a the given string or not, These operators are ‘in’ and ‘not in’ ‘in’ operator: It returns true if Particular character exi a character/substring exists in the given string. ‘not in’ operator: It returns true ifa character/substrin, To use membership operator in strin; of string type, i. in 1g does not exist in the given sting gs, it is required tt that both the operands used shi not in >>> 'y! in "Hello! False >>> 'HEL' in ‘Hello! “i Python being case-sensitive False >>> 'y! not in ‘Hello! True >>> 'H' not in 'Hello! False >>> stri="ny" >>> steing='my book! >>> strl in string True s required that Both the operands used sho EN HEAE 6.5.4 Comparison Operators You can use relational/comparison operators (©, <>, <5, =5, !5) to compare two strings Python compares strings using ASCII, rather UNICODE value of the characters. Unicode va are also called Ordinal Values, comparing the fi rts by comparing the first element from each sequence (character-by-character on St A pyton Sr Hfthey are equal, it oes on to the n afi80 ext element, and 5 nh subsequent elements are not considered (even i they ae iefinds elements lary” ° we get 8 "Mary" and str2 a Mac". The first two characters from str1 and str2 (M and Me pared. As they are equal, the second two characters (a and a) are compared. Since they are com : gre also equal, the third two characters (r and c) are compared. Because 'r’ has greater ASCII/ ae eve than" ts greater than str go> Net" ‘tie! palse >>> Néree" qrve spo tarrou” > "aron” qrve sop Might" >= "Left" True >>> “teeth” < "tee" False yp "yellow" <= "fellow" False 5o> Nabe" >" True In all the above examples, Python compares using values (called Ordinal Values). For most common characters, the ASCII and Unicode values are same. The table below gives the most common characters and their ordinal values: ‘Common Characters and their Ordinal Values Table 6. Characters ‘Ordinal Values "o' to '9° 48 to 57 ‘At to '2" 65 to 90 ——_=e 97 to 122 eir Unicode values, ur Ua eo 6.5.5 String Slicing Slicing is used to retrieve a subset of values. A slice of a string is nothing but a substring. This — substring is termed as slice. Chunk of characters can be extracted from a string using ice operator with two indices in square brackets separated by colon ({:}). The syntax is: Syntax: String_name [start:end:step] Here end is excluded fA ring by returning characters falling between the \d this operation through examples: Sta first line of the code shows a string having 4 Python will return a slice of the sti position till end-1. Let us understan‘ Example 1: Consider the given code, the alphabets in the uppercase. Window Help File Eét Format Run Options alphabet_string “RBCDEFGHIJKLMNOPQRSTUVWKY2" sliced_string = alphabet_string[6:15:1) print (alphabet_string) print (sliced_string) Tae a) Tree SY [aL Tere Dm [nfole [oles |r fulviwlxty]z alphabet_string his particular string nt is going to extract a slice out of tl 4° position instead of 15% position as shown below, The second stateme from the 6" position and points to 1 File Edt Format Run Options Window Help alphabet_string = WABCDEFGHIJKEMNOPQRSTUVWXYZ" Sliced string = alphabet_string[§:15:1] print (alphabet_string) print (sliced_string) a Ge 8 seu Aee Os we ele es Asi cole Flea Pee lMyy ol Toles Trfulv|w]xtviz alphabet. string — "4 2 >>> RESTART: C:/Users/preeti/AppData) py ABCDEFGHIJKLMNOPQRSTUVWKY2Z GHIJKLMNO >>> Fig. 6.5{(a): String Slicing Using Step Value as 1 rs from index position ‘end’ position is to be excluded. Step 1 ensures that all characte the output as “GHIJKLM! position 14" are sliced out. Hence, statements 3 and 4 shall give own in Fig, 6.5(b), the output shall be obtainet In case the step value is taken as 2 as shi tt skipping the adia extracting a substring starting from 6" position to 14* position but element since step value is 2. len tyample 2: Consider the given figure: @ &) fit = aiphabet_string = “ABCDEFGHTaKtMNODORET, sliced_string = alphabet_string, -ORSTUVERY, yint (alphabet_string) ~ > print (sliced_string) 2 @s wy ww wn 2 ofelF [slays] [De [MPNfofPlolats Teele zw a5 alphabet_string Fig. 6.5(b): String Slicing Using Step Value as 2 «a the output displayed is “GIKMO" string A S|alvTe M Positive Index oli1{f2t3)4a?s 1.67 Negative Index sof[-9felal«elsltalsalabra >>> B=" SAVE MONEY" po> A[1:3] tay! Here print statement prints the subscript starting from index 1 and ending before index 3, so it will print av (1* and 2"* index), >> AL: 3) "sav" >>> Omitting the first index directs the Python interpreter to extract the substring till the second index starting from the beginning, ie. index 0. >>> A 131] "E MONEY" Omitting the second index directs the Python interpreter to extract the substring till the end of the string starting from 3" position. >>> A [2] "SAVE MONEY" Omitting both the indices directs the Python interpreter to extract the entire string starting from 0 till the last index. >> A [21] "Ey! For negative indices, the Python interpreter counts from the right side (also shown above). Here, start index is -2, but end index is not given, so it will start printing from index -2 and will print all the characters till the end (-2 starting point till index ~1). Omitting the first index directs the Python interpreter the beginning. Since the negative index indicates sli entire string except the last two letters is printed. (g) >>> Als: "sv to start extracting the cr cing from the end of the. Sh a This will print alternate character from the string. 6.6 STRINGS ARE IMMUTABLE Strings are immutable means that the content of the string cannot be created. Let us understand the concept of immutability with the help of ai >>>stri='Student' >>>str[3]='p! changed afy example, TypeError: 'str1' object does not support item assignment. Pyt Programmer to change a character in a string. As shown in the value ‘Student’. An attempt to replace ‘d’ thon does not alloy above example, strl he in the string by ‘p’ displays a TypeError, trings are immu! mice created, strings cannot be changed. 6.7 STRING METHODS AND BUILT-IN FUNCTIONS Python provides several built-in functions associated with the strings, These function uss to easily modify and manipulate strings. We can think of functions as being action we perform on elements of a string in our code. Built-in functions are pre-defined in P Programming language and are readily available for use. 1. Ien()—This method returns the length of the string. Syntax: len (str) Here str is the string. For example, >>> word='Good Morning! >>> len (word) oo? 12 fed >>> strl='This is Meera\'s pen! >>> len(str1) 19 2. capitalize()—This method returns the exact copy of the string with the first le uppercase, Syntax: str.capitalize() Here str is the string. for example, y stri='welcome? > jor sti capitalize () Welcome" yop stri capitalize () tyelcome" practical Implementation-3 write a ea in capital letter. " print (origi, str2="" X = strl.spiit for agian” | str2 += print (stra) a-Capitalize() a cio Fee (5 Set Debuy Options Wedew Hep python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (in -| tel)] on win32 f Type “copyright”, "credits" or "license()" for more information. >>> sreceeecersecassae=== RESTART! Cr\CHAPTER 6\prgm_2.py ==== Enter a string:we are learning python original string:we are learning python 3, split()—The split() method breaks up a string at the specified separator and returns a list of substrings. Syntax: str.split([{separator [, maxsplit]]) The split() method takes a maximum of 2 parameters: The separator is a delimiter. The string splits at the specified Ye ercr ose a .d, any whitespace (space, newline, etc.) separator. If the separator is not specific string is a separator. : ines the maximum number of splits. The default . i 1) The maxsplit defi ; maxsplit (optional) limit on the number of splits. value of maxsplit is -1, which means no ae example, >>> x= "blues red;greent >>> Xesplit (8) Ublue'y "zed", 'greent) >>> text='Love your country' >>> print (text.split()) {Etove", “*your*,” ‘countxy*) Here, separator is not specified, so by default, The second argument ‘maxsplit’ is optional an; ‘n’ is given for the second argument, Space isa string separatoy, d its default value j S Zer0, If the string is split into ‘n+1’ aN ita strings, >>> grocery= 'Red:Blue >>> Print (grocery. split URed', 'Blue', Oran; replace()—This function replaces all the occurrences of the old string with the ne Syntax: str. replace (old, new) >o> print (str2.replace (*co14", *hot")) Inot cottee find()—This function is used to search the first occurrence of the substring in the ge string. The find() method returns the lowest index of the substring if it is found nti given string. If the substring is not found, it returns ~1. Its syntax is str.find(sub, start, end) Here, sub: is the substring which needs to be searched in the given string start: starting position where substring is to be checked within the string end: end position is the index of the last value for specified range >>> word = ‘Green revolution® >>> result= word. find('Green') >>> print (result) 0 >>> result= word. tind (‘green") >>> print (result) 1 >>> resulteword. tind ("6") 4) >>> print (result) 7 >>> resulteword.find("en",5) 33> print. (result) oa er '0! >>> result-vord.tind("o!, 11,14) #Finding lett >o> print (result) # from Lith to 14th position a tement, letter ‘o’ j, e last St fe coer ois a be Searched for starts in 4th position, it will result in Starting fry ies es Ul search position, Since ‘o" index() This function 'S quite similar to fina Nand shall return <1 a ince ‘o" pot present in the given string, nd() but raises an except; as the output, “ption ifthe substring is syntax: index (substring, start, eng) sent = “ello 778 all abou Snears oS RE Taal O > strl-index (*11*) praceback (most recent call last); Sie "", line 1, "jy Peel. index ("Hi") ote |valueBrror? substring not found p> 1, isalpha()—This function checks for al Iphabets in an : | string contains only letters, otherwise inputted string, It returns True if the returns False. syntax: str.isalpha () >>> str = "Good" >>> print (str.isalpha()) True Returns True as no special character or digit is present in the string. ‘This is a string” isalpha()) >>> str. >>> print (st: False Returns False as the string contains spaces. >>> strlstworking with ...Byth >>> print (strl.isalpha(}) False Returns False as the string contains special characters and spaces. 8. isalnum()—The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letters (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space) ! # % & ? ete. Syntax: string.isalnum() For example, [texti= ‘Python 3.8" x = text14salnum() 10. 11. 12, > | ‘The above function shall return output as False since the text contains Space al so, ‘Texti=" pythons” text isalnun() print (x) 3 RESTART: C: /Users/preet: fune.py true As is evident from the second example, the output returned is Ty Ue since text i only text and numbers. isdigit()—This function returns True if the string contains only digits, otherwise Syntax: str.isdigit() >>> strl = "123456" >>> print (str1isdigit()) True Returns True as the string contains only digits. >>> strl = "Ran begged 1st posizion" >>> print (str1 isdigit ()) False Returns False because apart from digits, the string contains letters and Spaces, title()—This function returns the string with first letter of every word in the uppercase and rest in lowercase, Syntax: str.title() >>> strl = “hello ITS all about sTRINGS!!" >>> stri.title() ‘Hello Its All About Strings!!* >>> Thus, title() returns a version of the string where each word is titlecased. count()—This function returns number of times substring str occurs in the given st If we do not give start index and end index then searching starts from index 0 and at length of the string. F Syntax: str.count (substring, start, end) >>> strl = 'Hello World! Hello Hello! >e> strl.count (*Hello' , 12, 25) 2 >>> strl.count (‘Hello") 3 lower()—This function converts all the uppercase letters in the string into lowercast Syntax: str. lower () >>> strl= "Learning PYTHON" >>> print (strl. lower ()) learning python Converts uppercase letters only to lowercase return the string, >>> strl= "learning python" >>> print (strl,lower ()) learning python ill sil e. If already in lowercase, then it will i 16. nis function returns True if al Il the | i ters inthe string are in lowercase. apr ssvower() python” 2 segue istowr0) 7 seve oy = “pyenon” » pint {stri.isiower ()) > ” alse ype TH5 function converts lowercase letters in the string into uppercase. syntax: str.upper () sp varie ‘welcome! 2 pent (van) -oppeE() enon already n uppercase then it will simply return the string spp vari= "WELCOME! 2 print (varl upper ()) escONe isupper( syntax: str. isupper() }}—This function returns True if the string is in uppercase. ppp strl= "PYTHON" 33 print (str -isupper ()) ome p> strl= "Python" o> print (str1isupper ()) pals |srip()—This function returns the string after removing the space(s) from th string. Syntax: str.1strip() or str.istrip (chars) chars (optional)—a string speci combinations of characters in the chars argumen until left character of the string mismatches. >>> strl= " Green Revolution” >>> print (str1.1strip()) Green Revolution left of the fying the set of characters to be removed from the left. All tare removed from the left of the string Here no argument is given, hence, it removed all leading whitespaces from the left of the string, >>> str2= "Green Revolution” >>> print (str2.1strip("Gr". een Revolution 7 7 ae poe diese nace int (str2 strip ("26 een Revolution ge Here all elements ofthe given argument are matched with eft ofthe str2 and if found, are Temoved. * Tactical Implementation-4 Write a program that reads a line and prints its frequency chart like, Number of uppercase letters Number of lowercase letters Number of alphabets Number of digits lowercount = uppercount = 0 digicount = alphacount = 0 for a in line if asislower (I+ owercount += 1 elif aisupper(): uppercount += 1 elif avisdigit (ys digicount += 1 if a-dsalpha(): alphacount += 1 lowes (umber of uppercase letters :*, uppercount) st ("Nuxker of lowercase letters:", lowercount) , alphacount) 7 digicount) = ("Husber of alphabe' for BIG data 2020 letters : 5 str.rstrip (chars) chars (optional)—a string specifying the set of characters to be removed from the All combinations of characters in the chars argument are removed from the right o until the right character of the string mismatches. >o> stri= "Green Revolution * >>> print (stri.rstrip()) Green Pevolution Here no argument is given, hence, it removed all leading whitespaces from the right of t= © >>> strl= “Computers” >>> print (strl.rstrip("re")) Compute Here the letters ‘rs’ are passed as an argument; it is matched from the right of th removed from the right of the str1. ye SUID, 8 nett of the string. U a ot 10. a. __4_This function returns the str Ting after removing the Spaces both on the Jeft and syntax? ger strip () =" Hello 27S ali trl all abc 2 Seri. strsp0) out STRINGS!) Zeno 17S all ‘about STRINGS! ” ace()—This function returns True if the strin ise returns False. contains only whitespace characters, | syntax: str.isspace () po stele" 2} print (trl. isspace()) eve yoo strl=" Python" 33> print (str1.isspace()) False isle THe mee function doesn't take any arguments. It returns True if the string is properly “titlecased’, else returns False ifthe string is not a "titlecased” string or an empty string. Syntax: str. istitle() >> strl= "All Learn Python" Soo print (str1-istitle()) rue >>> s= "All learn Python” >>> print (s.istitle()) False >>> s= "This Is @ Symbol" >> print (s.istitle()) True >>> s= "PYTHON" >>> print (s.istitle()) False join(sequence)—This function returns a st joined by a string separator. Syntax: str. join (sequence) sequence—join() takes an argument which is of sequence data type, capable of returning its element one at a time. This method returns a string which is the , clement of the string and the string separator between each element of the string. >>> stri= 112345" po» str2= ‘abed -* >>> 8 ote >>> s.join(str2) 3 1 Speen eee Pepcta! tring in which the string elements have been concatenation of each » >>> str2= "PYTHON" 22, swapcase()—This function converts and returns all uppercase characters into jg, and vice versa of the given string, It does not take any argument. Syntax: str. swapcase() ‘The swapcase() function returns a string 1 >>> str "Welcome" >o> stri.swapcase () "WELCOME" ith all the cases changed. >o>_str2.swapcase () ‘python’ >>> s= "pYThoN" >>>. s.swapcase () ‘pyton" 23, partition(Separator) specified separator and return a tuple with three parts: Partition function is used to split the given string using 8 the «+ substring before the separator; + separator itself; + a substring after the separator. Syntax: str.partition (Separator) Separator: This argument is required to separate a string. If the separator is no returns the string itself followed by two empty strings within parentheses as tup >>> str3= 'xyz@gmail.com' >>> str3.partition(' ') ('xyzgmail.com', '*, '') Here separator is not found, so returns the string itself, followed by two empty tin >>> str2- "Hardworkpays" >>> str2.partition('work') (‘Hard', 'work', 'pays') Here str2 is separated in three parts: ‘Hard, 1) substring before separator, ie, 2) separator itself, ie., ‘work’, and 3) substring part after separator, i-e., ‘pays’. >>> strd= str2.partition('-') >>> print (strd) (Hardworkpays', '", '*) >>> strS= str3.partition("@") >>> print (str5) (xyz', "8", "gmail.com! ) 6.8 OTHER FUNCTIONS a internal storage or memory of the computer, the characters are stored in integet Vale specific value is used for a given character and it is based on ASCII code. There are dill numbers assigned to capital letters and small letters. vides WO functions for character encoding: ord() B: ord() and ehr(), _phis function returns the ASCII Unica le of the eh haracter, 8 . oy ord (1A) 65 eur —Ehs function returns the character repre amber go> cnr (97) ‘at che (66) >> tpt sented by the inputted Unicode/ASCII é a & memory BYTES vy asteng ia sequence of characters. s, wecanereate thom simply by enclosing characters in quotes (single, double or triple) + postive subscript helps in accessing the string from the beginning, + negative subscript helps in accessing the string from the end + “¥ operator joins or concatenates the strings on both sides of the operator. > the operator creates a new string concatenating multiple copies ofthe same sting > operator ‘in’ returns true if a character exists inthe given string. > operator ‘notin’ returns true if a character does not exist in the given string, > nange Slice gives the characters from the given range using to compare two strings. Youcan use (>,<,>=1<, strings character by character according to their ASCII values. > python compares two st that the content of the string cannot be changed after it has been created. > Strings are immutable means > There are many builtin functions for working with strings in Python len(), capitalize(),findl), etc. string using sep as the delimiter string. > Python provides various string functions lik > split) method returns alist of all words in the s' > upperl) method returns a copy of the string converted into uppercase characters. > Isdigit() method returns True if all ‘the characters in the string are digits, otherwise returns False. > count(}function will return the total count of a given element in 2 sting > index() function returns index position of substring, > strip() function performs both Istrip() and rstrip() on string. OBJECTIVE TYPE QUESTIONS 1. Fill in the blanks, (0) Astring isa {b) . (d) ‘+ operator of characters. 1g the string from the beginning. subscript helps in acces subscript helps in acce: the strings on both sides of the oper the string from the end. rator. (e) The.. method returns the lowestindex ofthe substring itis founding ¢ string. 0) suo function return the exact copy ofthe string withthe fistletter in yo (g) Strings cannot be modified as they are data types. (h) The sequential accessing of each of the elements in a string is called string... q _ Membership operator returns True if a character or substring exis 0 > (k) final) function returns 1-18. apart ofthe string containing some contiguous characters from yy _ when substring is not found in the main sr 0) _ method returns the lowest index of the substring if ts found in a giv (m) function is used to count how many times an element has occurreg Answers: (a) Sequence (b) Positive (c) Negative (d) Concatenates (e) find() (f) capitalize) (@) Immutable (h) Traversal (in (i) String slice 4 () find) (mm) count() 2. State whether the following statements are True or False. {a} An empty string is a string that has zero number of characters. {b) The last index number of string is length=1 or ~1. (c) “abc” * 2 will give abc*2 as output. (d) Multiplication operator (*) replicates the string. (e) We can combine two strings with the help of & operator. (f) When we compare “A” != “a”, it will give True as an output. (g) String allows forward and backward type of indexing. {h) In Python, ascl) function returns corresponding Unicode value of a character. {i) Size of "\" is 2. () Multiple ine string created with the help of triple quotes willinclude end line character inthe Answers: (a) True (b) True ——(c) False (d) True fe) False) (g) Tue —(h) False) False. = (i) True 3. Multiple Choice Questions (MCQs) (2) Which of the following is not a Python legal string operation? (i) ‘abe’ + ‘abe? (ii) ‘abet *3 ) ‘abe! +3 (iv) ‘abc lower (b) In Python, string + and * represents which of the following operations? Concatenation, Replication (ii) Addition, Multiplication Neither (a) nor (b) (iv) Both (a) and (b) (c) Which of following is not a valid string operation? (i) Slicing (ii) Updating (iii) Repetition (iv) Floor (4) How many times is the word “Python” printed in the following statement? S= ‘love Python’ for ch in s[3:8]: print('Python’) (i) 11 times (i) 8 times (ill) 3 times {iv) 5 times (¢) Which of the following is the correct syntax of String Slicing? (i) String_name{start : end] (ii) String_namefstart : step] (ii) String_namefstep : end] {iv) String_name[step : start] ~ wal e mn ae AISaay the lst our cha patil be the output of the following code? _ saa ae gqrte “love Python.” iv). str{/4:) strlen = len(str1) print(strlen) : 9 (ii) 29 an (a) What willbe the output ofthe following code? 4 ie stri= My name is digital” gtr2=Str1(3:71 strlen = len(Str2) print(strlen) a4 shod 14 ce i ch method removes , iv a a wer) fia ae whitespaces from the right ofthe string? {j) To concatenate means to (i) replicate (i) join answers: (2) (e) (iii) (iil) Istrip() (iv) strip) (ii) split {iv) multiply (b) (i) (e) (iv) (2) (iv ) (h) (i) () ti) () i) a QLD QUES TONS 4. What isa string? ns. Astting isa sequence of characters. We can enclose characters in quotes (single, double or triple). 2. What is a range slice function in string? ns Range Slice function gives the characters from the given range usin 3, What is traversing a string? ‘Ans. Traversing a string means accessing all the elements of the string one after the other by using the subscript/index value. 4, Consider the string str="Green Revolution”. Write statements in Python to implement the following: (a) To display the last four characters. (b) To display the starting index for the substring ‘vo. (q To check whether the string contains ‘vol’ or not, (d) To repeat the string 3 times. Ans, : (b) str. find (*vo") 8 (e) 'vol’ in str ‘True (d) ste*3 "Green Revolution Green Revolution 6H 5. What will be the output of the following programming code? x="Amazing" Print (x(3 Print (x{~ Print (x[2:7], "and", x[-4? Zing and Am ’maZing and Zi aaing and zin een Revolution" 6. Consider the following code: STRI=input ("Enter a string:") while len (STR1) <=4: if STR1[-1]=='z STRI=STRI(0:3]+"c" elif ‘a’ in STRI: STR1 = STRI[0]+"bb* elif not int (STR1[0])+ 5 STR1 = 'I'+STRI[1:]+'2" =STRI+'*" print (STR1) What will be the output produced if the input is: (a) tbzz (b) abcd ‘Ans, (a) 1bzc* (b) endless loop because ‘a’ will always remain atin, 7. Write the output of the following code when executed: Text="gmail@com" I=len (Text) 2 ntext="" for i in range (0,1 if Text [i] .isupper() : ntextentext+Text [i] .lower () elif Text [i] .isalpha(): ntext=ntext+Text [i] upper () else: ntext=ntext+'bb! print(ntext) Ans. GMAILbbCOM 8, How many times is the word ‘HELLO’ printed in the following statement? s="python rocks' for ch in s[3:8]: print ("Hello") ‘Ans, 5 times 9, Find the output of the following: word = 'green vegetables! print (word. find('g’, 2)) print (word. find('veg", 2)) Print (word. find('tab', 4, 15)) ‘Ans. Output: 8 6 10 10. How can you create an empty string? Ans. An empty string can be created by using either double quotes ("”) or single quotes ("). 44. Astring called str contains whitespaces at the left of the string as given. str=" python Program" Write the command to delete the spaces, Ans. The commandis: str. Lstrip () 0 Strings strd.and str2are taken as “Delhi” and (ii) bval = (li) False StrLlower() < stra i) Fase p05 ee the Wor Wey in theilo!: 1 ‘hello’ letter by letter, bh e 1 1 ° t the numb st 2 242M 8 OURE TRE AUMBE of owl in he sting pingapl cole: yord count = for letter in wort gp detter in ('2", tut, tar, rer, "pineapple! int (count) pe output: 4 15. Conyou sort a list which contains both numeric and string data? ns. No the sort() method will raise an error called unorderable types: int) < sr). 16, What will be the output of the following program snippet? aNDarTe’ str nstr for i in range(len(str)): if str[i].isupper(): nstr = nstr + str[i].lower() els nstr = nstr + str[i].upper() print (nstr) ‘ns, The output is: AndARGEL \Write a program to check whether the string Is a palindrome or not. Ans, Code: str=input (" IsLen (str) pel-1 inde: while (index>> print (x[1:-2]) 5. Write the output of the following: "Hello Madam, I love Tutorials" >>> x (a) string substring = "Madam" if string. find(substring) !=-1: print ("Python found the substring! else: print ("Python did NOT find the substring! (b) s print(s.capitalize()) print(s.title(}) s6=s.replace("in", "data type") print(s6) ‘Strings in Python" 6. Find the output of the following: word = 'work hard" result = word. find('work') print("Substring, 'work', found at index:", result ) result = word. find ("har') print ("Substring, ‘har ' , found at index:", result ) if (word.find('pawan') != -1): print("Contains given substring ") else: print ("Doesn't contain given substring" Consider the following string mySubject: mySubject = "Computer Science" What will be the output of the follo i string operations? (i) print (mySubject [0: len (mySubject) }) (ii) print (mysubject [-7:-1]) (ii) print (mySubject (::2]) (iv) print (mysubject [1en (mySubject)-1]) (v) print (2*mysubject) (vi) print (mySubject [::-2]) (wi) print (mysubject [:3] + mySubject [3:]) (vii) print (mysubject.. swapcase()) (x) print (mysubject.startswith (*Comp') ) (¥) print (mysubject .isalpha()) tne thon statement and the output for the ‘& wed the third occurrence of ‘ein ‘sequence’, (a) change the case of each letter in string ‘FuNcTion’ OO) peter 2 exists In sting ‘Schoo!’ of not. : the string str1="Global Warming”, ents in Python to implement the following: ete ply the ast four characters e To replace all the occurrences of letter ‘ain the string with ith “00 output of the following program code: . tyirus-virus-virus! 4 following: ( idet consi 9, co tte yo write th ae . tr ["Fundamentals", "of", "Python") =m" #no space ai print (d1-Jo!n ({str)) gy, What will be the output of the following code? qext = "Mind@Work!" ja = len(Text) aText = "" for i in range(0,1n): if Text [i] -isupper(): nfext = nText + Text[i].lower() elif Text[i] .isalpha/( nText + Text (i].upper() " 4 nText else: nfext + 'A' nText print (nText) tninputthe string ‘My School’. Write a script to partition the string atthe occurrence of letter W. 12. Wite a program to convert a string with more than one word into titlecase string where string is passed asparameter,(Titlecase means that the fist letter of each word is capitalized) 14, Write a program that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence. 15. Write a script to partition the st 16. What will be the output of the following programming code? ring ‘INSTITUTE’ at the occurrence of letter str="My Python Programming" print (str ({-5:-1]) print (str[1:5]) print (str[:-4]) print (str[0:]) Print (str[:13-4]) Print (str[:3]) 17. Write a program to count the number of each vowel in 2 given S108: 18. Write a program that reads @ line, then counts how many times the word ‘is’ appears in the line and displays the count. 18. Write a program to remove “if any) from a string 4 ) CASE-BASED/SOURCE-BASED INTEGRATED QUESTIONS 2, Ans. 1, ABC Dialling Networks Pvt. Ltd. is a company that deals in maintaining the Phone customers globally. It prefixes the area code automatically at the time of adding the phone its database. is ‘Write a program that prompts for a phone number of 10 digits and two dashes, a dash each ap code and the next three numbers, For example, 017-555-1212 is a legal input. Display if ¢y number entered is a valid format or not and if the phone number is valid and not (i.e., contai digits and dashes at specific places). Jp sinput (renter Phone Nesber fal = False 12 and pis) == pit : sptaeT) spl8z)) ssdight 0 fall the characters except dashes should be aigits “print (pyis valid) ‘eine (py"is Snvalld") > RESTART: C:/Users/preeti/AppData/Local/ casestudyl.py Enter Phone Number :223098088 223098888 is invalid >>> RESTART: C1/Users/preeti/AppData/Local/ casestudy1.py Enter Phone Number 989-234-3377 989-234-3377 is valid . Kids Elementary Technologies help nursery children to improve their handwriting and writing skills such as word formation, recognition of lower and uppercase letters and small sentences formation, Write a program that should prompt the child 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): * Number of words ‘+ Number of characters (including white-space and punctuation) * Percentage of characters that are alphanumeric nunber_of_characters = 1en(s) jal_nun = 0 for i in sz if iisalnun0: ‘al_num += 1 ‘'z @ there is a space means there is another vord ____ Runber_of_vords += 1 print ("number Of Words are”, number_of_vords) jprint ("nunber_of_characters are” number_of_characters) [print ("percentage of characters that are alphanumric {s",al_num*100/1en(s),"8") ind 3 RESTART! C:/Users/preeti /appData/Local /Prograns/Python/Py! Je_paraneters.py enter a sentence : This Utility is for Nursery KIDS Inunber of words are 6 nunber_of_characters are 32 percentage of characters that are alphanumric is 64.375 +

You might also like