0% found this document useful (0 votes)
3 views

6.(Strings in Python)

The document introduces strings in Python, explaining that they are sequences of characters enclosed in quotes. It covers how to create strings, including empty and multiline strings, and discusses string traversal using indexing and loops. Additionally, it highlights string manipulation using operators like concatenation and repetition.

Uploaded by

Varun kumar
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)
3 views

6.(Strings in Python)

The document introduces strings in Python, explaining that they are sequences of characters enclosed in quotes. It covers how to create strings, including empty and multiline strings, and discusses string traversal using indexing and loops. Additionally, it highlights string manipulation using operators like concatenation and repetition.

Uploaded by

Varun kumar
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
You are on page 1/ 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: pe" to the user that combines with his/her name. ¢ ame, cy “ong La prog. sie py - cyUsers/preeti/AppData/tocal/rogramy.. ~ © KIER 4 fie 4 fost fan Options Wd hp print ("Enter your name: ") 7 ame = input () print (*Hello"+nama) Fie {8 Shel Debug Optane Widow Help python 3.6.5 (v3.6.5:£59¢0932b4, Mar 28 2018, 1- 6207346) (MSC v.1900 32 bit (Intel)} on win3e Type "copyright", “credits” or "license()" for more information. >>> vw RESTART: C:/Usors/preeti /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 number 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. 6.2 WHAT ARE STRINGS In Python, a consecutive sequence of characters, which are enclosed or surrounded by sing €') or double (“") quotes, is known as a string, This sequence of UNICODE characters 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 String Python treats single quotes the same as double quotes, i ‘ ‘ y_string = "Python Strings" Triple quotes are typically used for strings that span Lita atta multiple lines. For example, Fruit jango Apple Grapes’ Im 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 ' ' + : 5 1 ings Tepresenting a string value assigned to the variable ‘Fruits’, Like other integer variables, st are also declared in the same manner using ‘ 6.3 CREATING STRINGS p Strings are among the most popular data types in Python. We can create them ee, enclosing characters in quotes (single, double or triple). Python treats single quotes Me 4 as double quotes. Sometimes, triple quotes can be used in Python but they are ea 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. =" operator. | | le, ean " ff ello world’ & rogramming" f 17 python PI s Window Hep 59c0932b4, Mar 28 2018, 1 y C v.1900 32 bit (Intel)] on win32 copyright", “credits” or e re information. go» az "Good Morning" ma ‘good Horning’ "license ()" for = yp» a= ‘Good Horning’ ext can be enclosed within single cr double quotes, both are treated as strings. ya ‘good Horning’ support a character type; python does no! considered a substring. 1p 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.53 6:07:46) [MSC v.1900 32 Type “copyright”, more information. yop am Nirite article on \'AI\" briefly " o> print la} ‘Write article on wart 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° ae python 3.6.5 (3.6.5: 889c0s3apq 6:07:46) (usc V.1900 32 bit Cnteny a ata Type "copyright", “credits” saues more information, >>> a= "Good Morning" >a "Good Horning’ 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 Morning! fython 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 QO" 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 Siew “SSS ate cuotes ides srng by 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 Edt 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 iesorsa6) tase ScoeteBeO8REDT, Mar 28 2018, 3 2 bit (Intel)) on wind Type “copyright”, credits» r more information or "License()" fo o> als"iane\t class \t section >> al*RIA\ Mt oY >> print (at jae class section >> print a2) am ou 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 J example''" J>>> print (s) this isa [nultiline string example dep ge ttt we aze studenss Jwe study computer science Jprogreming language 42 python’ >>> print(s) we aze students we study computer science progranning language 18 python >> pei aH aay c jequence ingle double or tiple). shaenatenoe eas 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 ach character ina string is located in diferent slots (like Lacks): 85 Stowe In ach chara For example, Consider a string as: "hello world!" str hleftit|o wlofrjtid}! 0123456789101 b Fig, 6.3: Character Representation in 2 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) w >>> 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 fo yn Positive Index Ce ea ees 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 ee | a1 co Wofoo ford [al Positive Index 9 | ie PaelRaclisa | ef rafaa] 9 Negative Index 2] -1|-10[ -9 fe) afoetsf als ating enroult Stig Using for Toop ring can be accessed se er of the aract aque cl erating: 0 nitia ie in path lea erating ver I results tn disp 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. by erating through string (String Traversal) sing 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 _Formst Run Options Wind >>> 1 #string traversal using while loop . RESTART?) strl = "Python Programming!" essl.py | index = 0 P | Hlen() function to get length of string Ny while index < len(strl): G | print (str1 [index] ,end = *"\n") n | index += 1 ° cindex += 00 tn | 2 | | r | ° | g | r | a | mm | n | i | n | | : | i t Practical impte Write a program to count the number of occurrences of Complementing string traversal) |trunction to count the number of times a character occurs ing i fstring (ste = input ("Enter a string: ") ich » input ("Enter the character to be searched: " count = 0 ‘for character in str: b if character == ch: count 4= 1 [print ("wunber of times character", ch, “occurs in the string \ count) Mentatlon-1 a character in an inputteg s ing ac /Users/preeti /appData/Local/Programs /Python mn 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, |PProgram to display string In reverse order str = input ("Enter a string: ") for & in range (-1,-1en(str)-1,-1): print (str[i),end=" ") > 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} erators like concatenate (+), repetition ( operator like in and not in, *) and membership (Tse TD snstano Ca (cere) sting sing orenons GE seen i Common String Operations apa shel Debug Options Window Help a fi enon 3-6-5 (36-8: £59¢0932b4, Mar 99 0 32 bit (Intel)} on win32 “8 2018, 16307346) ope “copyright, “credits (" oon BC val Conse ()" for more i vp eo '4*Korla! hformatiion, Jyello World" > ce"Good " —” Morning 2 print (c) Good Morning —_—_————— to add an integer value toa string, it will gel ed by Python interpreter in case of incomps wef generat erate an error, ie atible data types as shown below: ie tat Shel Debug Opt Window Hep python 3.6.5 (v3.6.5:£59c0932b4, Mar 26 D0I% 900 32 bit (Intel)} on win32 ea 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 ' >>> 2e'2" 129" For replication operator *, Python creates a new string that is a number of repetitions of the put string, ‘Typekirror will be ud “or example, | thon’ >>> str * 3 fusing variable str ‘PythonPythonpython* >>> gh Fist Traceback (most recent call last): File "", line 1, in 13) 8 154 TypeError: can't multiply sequen Te 5 opt To ee hve bh op aa ction) oF one string type and one number type (for replication) t connor yo operands of string types. mes ‘The last statement shall result in an error because strin; 85 cant be multiplied one ope to be an integer value, eran has 6.5.3 Membership Operators Python offers two membership operators for checkin ig whether a the given string or not, ‘These operators are ‘in’ and ‘not in’, Particular character exi ‘in’ operator: It returns true if a character/substring exists in the given string. It returns true if a character/substrin, To use membership operator in strin; of string type, i. ‘not in’ operator: 8 does not exist in the given string 8s, itis required that both the operands used sh in 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 >>> stris"ny" 22> steing='my book! >>> strl in string True s required that Both the operands used should b paraer 6.5.4 Comparison Operators You can use relational/comparison operators © <>5, tes" "tie! palse po Néree" qrve > tarrou” > "Yaron" qrve sop Might" >= "Left" True >>> “teeth” < "tee" False go> "yellow" <= "fellow" False spo 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 "9" to *9" 48 to 57 ‘A’ to '2" 65 to 90 ——_=e 97 to 122 eir Unicode values, ur Uae 6.5.5 String Sticing 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 4 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 Edt Format Run Options alphabet_string “RBCDEFGHIJKLMNOPQRSTUVWKY2" = sliced_string = alphabet_string{6:15:1) print (alphabet_string) print (sliced_string) Tee DAR ewe Tree SY [aL Tete Dw [nfole [ote ls |r fulviwlxty|z alphabet_string his particular string s 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) fae Qe 8 seu Mee as i eee oe npGoG F[efaL Lee Mysore Toles Trfulv|w]x}viz ‘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 dia extracting a substring starting from 6" position to 14* position but element since step value is 2. len syample 2: Consider the given figure: @ ) fit = aiphabet_string = “ABCDEFGHTKIMNODORET, sliced_string = alphabet_string, ORS TUVEKY. yint (alphabet_string) ~ > print (sliced_string) Os ey www ne ofelF [slays] [Te [MPN fofPlolats Teel zw as alphabet_string Fig. 6.5(b): String Slicing Using Step Value as 2 va the output displayed is “GIKMO" string A S|alvTe M Positive Index oli1l2t3)a?s 1.67 Negative Index sof/-9felal«elslalsalatra >>> B='SAVE MONEY" po> AL 1:3] tav! 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 [-2:] "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 tostart extracting the cr cing from the end of the. Sh 2 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, strings 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 us 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 aad >>> strl='This is Meera\'s pen! >>> len(str1) 19 2. capitalize()—This method returns the exact copy of the string with the first et uppercase, Syntax: str.capitalize() Here str is the string. for example, yp 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 fon aaa | ° | str2 += print (stra) a-capitalize() a cio Fie {Bt 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 ype “copyright”, "credits" or "license()" for more information. >>> sreceeeeceraesassae=== 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 Meera ae 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 atl example, >>> x= "blues redigreent >>> Xesplit (8) Ublue'y ‘red*, 'greent) >>> text»! Love your country' >>> print (text.split()) {Etove", “*your*,” Ycountry*) 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 separator, d its default value i 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 Inti 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 ("e", 4) >>> print (result) 7 >>> resulteword. find ("en",5) 33> print. (result) oa er '0! >>> result-vord.find("o!, 11,14) #Finding Letts >>> print. (result) # from Lith to 14th position a tement, letter ‘o’ j, e last st feo ee otis 2 be Searched for starts in 4th position, it will result in Starting fry ies ah Ul search position, Since ‘o" index() This function 'S quite similar to fina Nand shall return <1 a ince ‘0" not present in the given string, Nd() but raises an except; as the output, “ption ifthe substring is syntax: index(substring, start, eng) seni = “ello 775 all abou Sanears oe RE aetna O > strl-index (*11*) raceback (most recent call last); Sie "", line 1, "jy Pete. index ("Hi") = eestibae |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. ooo strlstworking with ...Fyth >>> print (str1.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" texti.isalnun() print (x) Ey 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. >>> str] = "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!!" >>> strl.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. this function returns True if al Il the | i ters inthe string are in lowercase. apr ssvower (0 python” 2 gest istowrO) 7 eve ay = “pyenon” ” paint {stri.isiower ()) > ” alse apper—TH5 function converts lowercase letters in the string into uppercase. syntax: str.upper () sp varie ‘Wehcone! > pent (van) appr ()) enon already n uppercase then it will simply return the string, spp varl= "WELCOME! 2% pint (varl upper ()) escOne isupper( syntax: str.isupper () )}—This function returns True if the string is in uppercase. ppp strl= "PYTHON" 33 print (str1 -isupper ()) ome p> strl= "Python" o> print (str1-isupper ()) ralse \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 e 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 oe foe ome havc int (str2 strip ("26 een Revolution oa. Here all elements ofthe given argument are matched with let ofthe str2 and, f 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 (J+ Jowercount += 1 elif a.dsupper(): uppercount += 1 elif avisdigit(): digicount += 1 if a-dsalpha(): alphacount += 1 lowes ec (iuxber of uppercase letters :*, uppercount) st ("Nuxker of lowercase letters:", lowercount) , alphacount) 7 dighcount) = ("Husker of alphabe' for BIG data 2029 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 ene of the string. U a ot 10. a. __ This function returns the stri Ting after removing the Spaces both on the left and syntax? ger strip () =" Hello 17S ali trl all abs 2 Seri. strsp0) out STRINGS! Zanio 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 (stri.isspace()) eve go> strl=" Python" 33> print (str1.isspace()) False iste 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() yo strl= "All Learn Python" So> 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" >>> str2= ‘abcd! -" >>> 8 oot >>> s.join(str2) 3 1 arenes Tepcta! 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 w' >>> strl= "Welcome" >o>_ stri.swapcase () "WELCOME" ith all the cases changed. >>> str2.swapcase () "python! >>> g= "pYThON" >>> s.swapcase () "python" 23, partition(Separator) specified separator and return a tuple with three parts: + substring before the separator; + separator itself; Partition function is used to split the given string usiy + a substring after the separator. Syntax: str.partition (Separator) Separator: This argument is required to separate a string. If the separator is not found returns the string itself followed by two empty strings within parentheses as tup >>> str3= '[email protected]' >>> str3.partition(" ') ('[email protected]', '", "") Here separator is not found, so returns the string itself, followed by two empty string >>> str2= "kardworkpays” >>> str2.partition('work') (‘Hard', ‘work’, 'pays') Here str? 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) (CHardworkpays', '", '") >>> strS= str3.partition("@") >>> print (str5) xyz", '@", "gmail.com! ) 6.8 OTHER FUNCTIONS a internal storage or memory of the computer, the characters are stored in integer 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 /Uniea le of the eh haracter, 8 . Sy ond (1A) 65 eur —Uhls function returns the character repre amber go> cnr (97) ‘at che (66) >> tpt sented by the inputted Unicode/ASCII é ao & memoRY BYTES + asteng sa sequence of characters. 1, 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 ifa character does not exist in the given string, > nange Slice gives the characters from the given range using to compare two strings. Youcan use (>,<,2=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. 1 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. method returns the lowestindex ofthe substring itis founginy ¢ ) suo function returns the exact copy ofthe string withthe fistletter jn 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... iO) . Membership operator returns True if @ character or substring eg 0 > (k) final) function returns 118 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 itis found in a giv (m) .funetion is used to count how many times an element has occurreg Answers: (a) Sequence (b) Positive (c)_ Negative (d) Concatenates (e) find() (f) capitalize) (2) 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. () “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, asc() function returns corresponding Unicode value of a character. {i) Size of "\" is 2. i) Muttipl ine string created with the help of triple quotes willinclude end line character inthe Answers: (a) True (b) True ——(c) False (d) True (@) 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= ‘Tove Python’ for ch in s[3:8]: print('Python’) (i) 11 times (ii) 8 times (ill) 3 times (iv) 5 times (6) Which of the following isthe correct syntax of String Slicing? (i) String_name(start : end} (ii) String_namefstart : step] (ii) String_namefstep : end] {iv) String_name[step : start] ~ u i al e mn ae AISBaY the lst our ena Wpatail be the output of the following code . seta ae gqrte “love Python.” iv). str{/4:) strlen = len(str1) print(strlen) : wo (ii) 29 an (a) What willbe the output ofthe following code? 4 ie stri= "My name is digital” gtr2=Str2 (3:71 strlen = len(Str2) print(strlen) a4 shod wy 14 (iy 28 i ch method removes ’ iv a “ ewer) in 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 1. What sa string? ans, Astring isa sequence of characters. We can enclose characters in quotes (single, double or triple). 2. What is a range slice function in string? ans 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'. (0) 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? xe"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 STRI[-1]=='z STRI=STRI(0:3]+"c" elif ‘a’ in STRI: STR1 = STR1[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(): ntextsntext+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 str1.and str2 are taken as “Delhi” and (ii) bval = (li) False StrLlower() < stra i) Fase 108 othe Or Wey in thello!: 1 ‘hello’ letter by letter, bh e 1 1 ° t the numb st 2 242m OURE TNE AUB of owen he sting pineapl cole: vord count = for letter in wort gp detter in ('U", tut, tar, ter, "pineapple! int (count) pei 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) < str). 46, What wil 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 (" ILen (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:]) (vil) print (mysubject.. swapcase()) (i) 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) Mpethet 2 exists In sting ‘Schoo!’ of not. : the string str1="Global Warming”, ents in Python to implement the following: wet ply the ast four characters e a To replace all the occurrences of letter ‘ain the sting with ith “00 output of the following program code: . tyirus-virus-virus! 4 following: ( idet consi 9, co tte yo write th ae . ur ["Fundamentals", "of", "Python" =m" #no space ai print (d1-Jo!n ee | gy, What will be the output of the following code? qext = "Mind@Work!" ja = len(Text) aText = "" gor 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) tn input the string ‘My Schoo. Write a script to partition the string atthe occurrence of letter W. 13. Wite a program to convert a string with more than one word into titlecase string where sting 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 S178: 1. 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 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. , 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 @ legal input. Display if number entered format or not and if the phone number is valid and not (i, nt a eae 2d ota) on sos and pit oe te Sa at arian cep eeaae saa 5 | co >>> ‘J RESTART: C:/Users/preeti /AppData/Local/ Enter Phone Number :223098888 casestudyl.py 223098888 is invalid >>> RESTART: C1/Users/preeti/AppData/Local/ casestudy1.py Enter Phone Number :989-234-3377 989-234-3377 is valid 2. 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 Ans. unber_of_characters = len(s) jal_nun = 0 for i in sz if iisalnun0: ‘al_num += 1 ‘ "2 @ there is a space means there is another vord ____ Rusber_of_vords += 1 print ("nunber 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 number of words are 6 nunber_of_characters are 32 percentage of characters that are alphanumric is 04.375 ¢

You might also like