Python Strings - Computer Science PDF
Document Details
![IntricatePlanet6345](https://quizgecko.com/images/avatars/avatar-2.webp)
Uploaded by IntricatePlanet6345
Tags
Summary
This document provides a comprehensive introduction to strings in Python, including various string operations, indexing, slicing and inbuilt functions. It demonstrates examples and exercises that may be useful for computer science undergraduate students learning about string manipulation
Full Transcript
COMPUTER SCIENCE WITH PYTHON [STRINGS] STRINGS ✓ Strings are a contiguous set of characters enclosed within quotes. ✓ The quotes can be single, double, or triple. EXAMPLES OF SRTING s="maps" r='1234' k="s2/234 kk"...
COMPUTER SCIENCE WITH PYTHON [STRINGS] STRINGS ✓ Strings are a contiguous set of characters enclosed within quotes. ✓ The quotes can be single, double, or triple. EXAMPLES OF SRTING s="maps" r='1234' k="s2/234 kk" INDEXING IN STRINGS Each character in a string is automatically assigned an index number. Two sets of indices are used in Python. Positive integers are used to index from left to right. Negative integers are used to index from right to left. Character H A P P I N E S S Index from left to right 0 1 2 3 4 5 6 7 8 Index from right to left -9 -8 -7 -6 -5 -4 -3 -2 -1 str1 = "HAPPINESS" print(str1[2:5:1]) → PPI print(str1[2:6]) →PPIN print(str1[::]) →HAPPINESS print(str1[:7:]) → HAPPINE print(str1[2:7:2]) → PIE print(str1[-3:-8:-1]) ➔ ENIPP x='COmpUtER' 0 1 2 3 4 5 6 7 C O m P U t E R -8 -7 -6 -5 -4 -3 -2 -1 print(x[1:4]) → Omp print(x[1:6:2]) → Opt print(x[3:]) → pUtER print(x[:5]) → COmpU print(x[-1]) → R print(x[-3:]) → tER print(x[:-2]) → COmpUt STRINGS: IMMUTABLE DATA TYPE ONCE CREATED CANNOT BE CHANGED St1 = "Information" print(St1) → Information print(St1[-5])→ a St1 = 't' ➔ error Page 1 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] >>> a= "python program" >>> a 'p' >>> a= "b" >>> a 'p' Name="Michael Jackson" Name= "T" → Error Name = Name + "is the best" ➔ OK ESCAPE SEQUENCE \n newline \t tab \" double quotes \' single quotes What are the different ways to assign the message: Hello, "How are you"? in a variable str? str = 'Hello, "How are you"?' str = "Hello, \"How are you\"?" str = '''Hello, "How are you"?''' STRING OPERATIONS Expression Results Description 'Hello! ' + 'Friends ' HelloF riends Concatenation -joins the strings into a single string 'Hello' * 2 HelloHello Repetition -repeats the string 'e' in 'Hello ' True Membership -retuns True if the 'h' in 'Hello' False character is a member of string 'h' not in 'Hello ' True otherwise False. STRING SLICING Slicing is an act of extracting a piece of a string from the original string. The general format is: str [startlndex : pastlndex] This refers to the substring of str starting at startIndex and stop before pastIndex. If you omit the startIndex, substring starts from the beginning (0th location). If you omit the pastIndex, substring starts from the startIndex and goes to the end. Page 2 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] INBUILT FUNCTIONS S.No. Name Description Example 1 len() This method returns the word="hello world" length of the string. len(word) Output: 11 2 capitalize() It returns the copy of the str="hello" string with first letter print(str.capitalize()) capitalized. Output: Hello 3 title() It returns a new string with str = “hello world” first character of each word print(str.title()) capitalized Output : Hello World 4 lower() It returns a copy of the string str="HeLLo" converted to lowercase print(str.lower()) Output : hello 5 upper() It returns a copy of the string str="HeLLo" converted to uppercase print(str.upper()) Output : HELLO 6 count() This function returns the str1="Hello World! Hello Hello" number of time substring str str1.count('Hello',12, 25) occurs in the given string. If Output : 2 we do not give start index and end index, then str1.count('Hello') searching starts from index 0 Output : 3 and ends at length of the string. 7 find() It returns the lowest index in str="hello" the string where the print(str.find("l")) substring is found within the Output : 2 slice mentioned. If not found, it returns -1. str="hello" print(str.find("l",3)) Output : 3 8 index() This function is quite similar to find() function as it also searches the first occurrence and returns the lowest index of the substring if it is found in the given string but raises an exception if substring is not present in the given string. 9 endswith() This function returns True if a='Artificial Intelligence' the given string ends with the a.endswith('Intelligence') specified substring else True returns False. a.endswith('Artificial') False Page 3 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] 10 startswith() This function returns True if a='Machine Learning' the given string starts with a.startswith('Mac') the specified substring else True returns False. a.startswith('learning') False 11 isalnum() It returns True if the string is str="hello" alphanumeric, otherwise print(str.isalnum()) False. Output : True str="***&&" print(str.isalnum()) Output : False 12 isalpha() It returns True if the string str="hello" has only alphabets, print(str.isalpha()) otherwise False. Output : True str="hello1" print(str.isalpha()) Output : False 13 isdigit() It returns True if the string str="123" has only digits, otherwise print(str.isdigit()) False. Output : True str="h221" print(str.isdigit()) Output : False 14 islower() It returns True if the string str="abc" has only lowercase print(str.islower()) alphabets, otherwise False. Output : True str="Abc" print(str.islower()) Output : False 15 isupper() It returns True if the string str="ABC" has only uppercase print(str.isupper()) alphabets, otherwise False. Output : True str="Abc" print(str.islower()) Output : False 16 isspace() It returns True if the string str=" " has only whitespaces, print(str.isspace()) otherwise False. Output : True str=" & " print(str.isspace()) Output : False Page 4 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] 17 lstrip() This function returns the str=" Green Revolution " string after removing the str.lstrip() space(s) from the left of the Output : 'Green Revolution ' string. st="Python Program" st.lstrip('Py') Output : 'thon Program' st.lstrip('yPt') Output : 'hon Program' st.lstrip('pY') Output : 'Python Program' 18 rstrip() This function removes all str=" Green Revolution " the trailing space(s) from str.rstrip() the right of the string. Output :' Green Revolution' st='Computers' st.rstrip('ser') Output : 'Comput' st='Computers,-.,...' st.rstrip(',.') Output : 'Computers,-' 19 strip() This function returns the str=" Green Revolution " string after removing the str.strip() spaces both on the left and 'Green Revolution' the right of the string. 20 split( ) This method breaks up a x='blue;red;green' string at the specified x.split(";") separator and return a list Output: ['blue', 'red', 'green'] of substrings text='This is red pen' text.split() Output: ['This', 'is', 'red', 'pen'] USE OF ord() AND chr() METHOD IN STRING MANIPULATION ord()-This function returns the ASCII/Unicode (Ordinal) of the character. >>> ch= 'b' >>> ord (ch) 98 >>> ord ('A') 65 chr()-This function returns the character represented by the inputted Unicode /ASCII number. >>> chr (97) 'a' >>> chr (66) 'B' Page 5 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] STRING PROGRAMS 1. WAP to input a string and find number of spaces in it. st=input("Enter a string: ") c=0 l=len(st) for a in range(l): if(st[a]==" "): c+=1 print("Number of spaces in the string", c) 2. WAP to input a string and convert the string to toggle case. st=input("Enter a string: ") l=len(st) tst="" for a in range(l): if(st[a].isupper()): tst=tst+st[a].lower() elif(st[a].islower()): tst=tst+st[a].upper() else: tst=tst+st[a] print("Toggled string is" , tst) 3. WAP to input a string and replace every space of the string with hyphen -. st=input("Enter a string: ") l=len(st) hst="" for a in range(l): if(st[a]==" "): hst=hst+"-" else: hst=hst+st[a] print("Hyphened string is", hst) 4. WAP to input a string and create another string without having capital vowels in it. st=input("Enter a string: ") l=len(st) vst="" for a in range(l): if(st[a] not in ('A', 'E', 'I', 'O','U')): vst=vst+st[a] print("Sting with capital vowels is ", vst) Page 6 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] 5. WAP to input a string and count how many times a substring appears in it. s=input("enter a string ") USE OF SPLIT FUNCTION l=s.split() r=input("enter a substring ") c=0 for i in l: if i==r: c=c+1 print(c) 6. WAP to input a string and count how many words are starting from vowels also display these words. st=input("Enter a string: ") words=st.split() c=0 for x in words: if x in ["a","e","i","o","u","A","E","I","O","U"]: c+=1 print(x) print("Number of words starting with vowel", c) 7. WAP to input a string and display the longest substring in the given string. st=input("Enter a string: ") words=st.split() longest=0 for a in words: length=len(a) if length>longest: longest= length lword=a print("The longest word is", lword, "with length", longest) 8. WAP to input a string and check if string is a palindrome or not. s=input("enter a string ") l=len(s) j=l-1 f=True for i in range(0,l//2): if s[i]!=s[j]: f=False break j=j-1 if f==True: print("string is a palindrome") else: print("string is not a palindrome") Page 7 of 11 COMPUTER SCIENCE WITH PYTHON [STRINGS] STRING OUTPUTS N="ComPUteR"; l=len(N) r="" Orignal : ComPUteR print("Orignal : ",N) Final : cOMmuTEe for x in range(l): if N[x].islower(): r+=N[x].upper() else: if N[x].isupper(): if x%2==0: r+=N[x].lower() else: r+=N[x-1] print("Final : ",r) T="SaVE EArtH"; l=len(T) r="" print("Orignal : ",T) Orignal : SaVE EArtH for i in range(l): Final : s#ve#e@##@ if (T[i]=='A' or T[i]=='H'): r+='@'; elif T[i].isupper(): r+=T[i].lower(); else: r+='#' print("Final : ",r) MyText="ApEACeDriVE" ch="@" l=len(MyText) Msg="" Orignal : ApEACeDriVE print("\n Orignal : ",MyText) Final : @Ae@cCdDIie for cnt in range (l): if MyText[cnt]>='B' and MyText[cnt]