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

Unit 2

Uploaded by

marv hartigan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
40 views

Unit 2

Uploaded by

marv hartigan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
Chapter 2 String, List and Tuple 2.1. Strings A string is a sequence of characters enclosed in single or double quotes. Strings are a data type in Python for dealing with text. Also, Python has a number of powerful features for manipulating strings. Creating a string- A string is created by enclosing text in quotes. We can use either single - A triple-quote can be used for multi-line strings. Here are some examples: 8 = ’Hello’ print (s) #Output: Hello t ="Hello” print (¢) #Output: Hello m = ”"” This is a long string that is spread across two lines.””” print (m) quotes,', or double quotes ” #Output: This is a long string that is spread across two lines. Input Recall: For numerical input we use an eval statement with the input statement getting text, we do not use eval. The difference is illustrated below. Example: , but when num = eval(input(’Enter a number: ’)) string = input(’Enter a string: ’) #Output: Enter a number: 9 9 Enter a string: Hello Python Hello Python Note that the empty string ” is the string equivalent of the number 0. fT a £@ re ui CHAPTER 2. STRING, LIST AND TUPLE * . i i's optional ar It is a string with nothing in it. We have seen it before, in the print statement’s opt ‘gument, sep=", 2.1.1 Length ‘To obtain the length of a string (how many characters it has), we use the built-in function len(”...») For example: Length of the str: "Hello” L=len(Hello”) print (L) #Output: 5 Consider the following examples: Example (i): L=len("Python") print (L) #Output: 6 Example (ii); L=len(” Mathematics") print (L) #Output: 11 Example (iii): x=len('Good Morning’) print (x) #Output: 12 y=len(”KALYANRAO”) print(y) #Output: 9 Remark 2.1. The operators + and + can be used on sirings. The + operator combines two strings and this operation is called concatenation. The» repeats a string a certain number of times. Example 2.1. Using the operators + and * find "XY" + "pq, "X” +"9" +”Y" and” Hello” +5, Solution: We use the + operator combines two strings and « Tepeats a string a certain number of times, a="XY" 4 "pq" print (a) #Output: X¥pq _ CHAPTER 2. STRING, LIST AND TUPLE 33 x” 49" 4"¥" print (8) #Output: XOY t= "Hello”#5 print (t) #Output:HelloHelloHelloHelloHello Example 2.2. To print a long row of dashes. print (’-*25) #Output: 2.1.2 Indexing ‘We will often want to pick out individual characters from a string, Python uses square brackets to do this. The table below gives some examples of indexing the string s=’Python’, Statement [Result Description [0] P first character of s s{t} y second character of s s(-l] last character of s si-2) | second-to-last character of s A common error Suppose s="Python’ and we try to do s{12]. Python’ print (s{10]) #Output: Traceback (most recent call last): File ”D:\ python 1_1_2020\ Seminar on Sfotware \ P222.py”, line 48, in print (s{10)) IndexError: string index out of range ‘There are only six characters in the string and Python will raise the above error message. Example 2.3. Pick out individual characters from a string ‘Python’ to form ’PythonnohtyP” 8='Python’” Output Print (6) P Print (s{1]) y Print (s(2}) t Print (63)) b Print (64) ° oe > CHAPTER 2. STRING, LIST AND TUPLE print (s(5)) 5 print (s{-1]) n print (s(-2)) ° print (s{-3]) h Print (s[-4)) t Print (s(-5]) y print (s[-6)) P To become familiar with them, you may write simple programs performing arithmetic and logical operations using them. #Example: oper.py import math import numpy as np x=2 yed print (x + y * 2) = ‘Hello’ print (5 +s) print (3 * s) print (x == y) print (y == 2* x) #Output: 10 Hello Hello Hello Hello Hello False ‘True #Example: import math tring.py import numpy as np “hello world’ print (s{0]) # print first element, h print (s(1]) # printe print (s{-1]) # will print the last character #Output: h e d CHAPTER 2. STRING, LIST AND TUPLE ee #Example: string2.py import math import numpy as np "hello'+'world? print (a) a print (b) print (a{-1] + b[0]) #Output: helloworld hahaha ah Example 2.4. Write a program in Python that repeatedly asks the user to enter a letter and builds up a string consisting of only the vowels that the user entered. Solution: for i in range(5): input(’Enter a letter: ") sas+t print(s) #Output: Enter a letter: a a Enter a letter: e ae Enter a letter: i ae Enter a letter: 0 acio Enter a letter: eeiou >>> "eciow’ CHAPTER 2. STRING, LIST AND TUPLE MH 2.1.3 Slices The part of a String can be extracted using the slicing operation, Indexing uning, ala: b) extracts elements s{a] to s[b..1]. A slice is used to pick out part of a string. It behaves like a combination of indexing and the range function. The following are some examples. Example 2.5. Given the string s='abodefghij’ inder: 0123456789 letters: abcde f ghij Cateulate s{2: 5], s{: 5], s{6 :], s[—2 5}, s[:], 9[1 27:2), af Solution: We have a sting s='abedefghij’. >>> s="abedefghij’ >>> 82:5] #Output: ’ede’ # characters at indices 2, 3, 4 >>> s[:5] #Output: ‘abcde’ #first five characters >>> s[5:] #Output: fghij’ >>> s[-2:5] #Output: ” >>> al: ] #Output: ‘abedefghij” >>> s[1:7:2] ‘bee? #Output: ‘jihgfedeba’ # a negative step reverses the string Example 2.6. Write a program to pick out part of a string ‘hello world’. import numpy as np a = ‘hello world’ print (a[3:5]) print (a(6:) print (a5) print (a[2:8)) CHAPTER 2. STRING, LIST AND TUPLE #Outputilo world hello Ilo wo. Example 2.7. To extract a portion of the string by using strings are concatenated with the plus (+) operator, where as slicing (:). Solution: Here is an example: >>> string] = Press return to exit >>> string2 = the program >>> print stringl +” ” + string? Press return to exit the program >>> print string] [0 : 12] # Slicing Press return # Concatenation Example 2.8. Give an examples of repetition, append elements and Concatenation of strings and Sequences using some operators. ‘There are some of these operators are also defined for strings and sequences as illustrated below. >>> s = 'Hello’ >>> t = ’to you’ >>> a= [1,2,3] >>> print (3 +s) # Repetition Hello Hello Hello >>> print (3 * a) # Repetition (1,2,3, 1, 2,3, 1,2, 3) >>> print (a+ [4,5]) # Append elements (1,2,3, 4,5) >>> print (s + t) # Concatenation Hello to you >>> print (3 +s) # This addition makes no sense ‘Traceback (most recent call last): File” < Pyshell#9 >”, line 1, in? Print (n + 8) TypeError: unsupported operand types for +: int and str ——__——————— (CHAPTER 2. STRING, LIST AND TUPLE or, floating point and strings Example 2.9. Give and example of the comparison between anteger, floating P2 d converted to a common type before the Numbers of different type (integer, floating point etc.) are comparison is made. Otherwise, objects of different type # 2 considered to be unequal. Here are a few examples: >p>a=2 # Integer >>> b= 1.99 # Floating point po>eal? # String >>> print (a > 8) 1 >>> print (a == ¢) o >>> print (a > 6) and (a! = c) 1 >>> print (a > 6) or (a == 8) |. 1 2.2 Lists ‘The Python List is a general data structure widely used in Python programs. They are found in other languages, often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed and sliced. ‘The list can contain different types of objects, including other list objects. A list is similar to a tuple, but it is mutable, so that its elements and length can be changed. A list is identified by enclosing it in brackets.Here is a sampling of operations that can be performed on lists: >>> a= [1.0,2.0, 3.0] # Create a list >>> a.append(4.0) # Append 4.0 to list >>> print (a) (1.0, 2.0, 3.0, 4.0] i >>> a.insert(0,0.0) # Insert 0.0 in position 0 >>> print (a) (0.0, 1.0, 2.0, 3.0, 4.0) >>> print (len(a)) # Determine length of list 5 >>> al2: 4) = [1.0, 1.0] # Modify selected elements >>> print (a) (0.0, 1.0, 1.0, 1.0, 1.0, 4.0} CHAPTER 2. STRING, LIST AND TUPLE - Example 2.10. Write a program to print list and obtain their length. L= [1,2,3.4,5,6,7,8,9] print(L) print (len(L)) HOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9} 9 Input: We can use eval(input()) to allow the user to enter a list, Example 2.11. Write a Program enter 9 digits and pick the their elements. L = eval(input('Enter a list: °)) print(’The first element is ’, L{0]) print(’The last element. is ’, L{8}) print("The fifth element is ’, L{]) #Output: Enter a list: 1,2,3,4,5,6,7,8,9 ‘The first element is 1 ‘The last element is 9 ‘The fifth element is 5 Data types: Lists can contain all kinds of things, even other lists. Example 2.12. Write a program to print valid list and obtain their length. L=I5, 23.14, *xyz’, [12,3] print(L) print (len(L)) #Output:[6, 23:14, *xy2’, [1, 2, 3) 4 Corollary 2.1. (i) Indeaing and slicing:- These work exactly as with strings. Example 2.13. Write a program to print valid list and obtain the first item of the list and the first three items etc, >> L = [1,2,3,4,5,6,7] >> print (L[o]) >>> print( L[:3]) CHAPTER 2. STRING, LIST AND TUPLE 0 U1, 2, 3] >>> print(L[4:2]) Q >>> print (LL 1]) (1, 2, 3, 4, 5, 6) Corollary 2.2. Use of operators + and + in a list: The + operator adds one list to the end of another. ‘The * operator repeats a list. Example 2.14. Write a program, to combine and repeat a list >>> s=[1,2,3,4] >>> t=[5,6,7,8,9] >>> print (s+t) U1, 2, 3, 4, 5, 6, 7, 8, 91 >>> print (s#4) 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4) >>> print (tx3) (5, 6, 7, 8, 9, 5, 6, 7, 8 9, 5, 6, 7, 8, 9) >>> print (s+t*2) (1, 2, 3, 4,5, 6, 7, 8, 9, 5, 6, 7, 8 9] 2.3 Tuple 2.3.1 Defination ‘A tuple is a sequence of values. The values can be any type viz., numbers, floats, string etc., Members in tuple are indexed by integers. In simple word, a tuple is a comma-separated list of values. That list is enclose by parentheses. For Examples: >>> t= (lat, tbt, 'c', ‘at, te") >>> # Parentheses are not compulsory. >>> tis tat, ‘bt, ‘ct, td', ‘e! >>> # We can display the type of ‘tl’. >>> type(t1) tuple() is a inbuilt function that converts any sequence(string, list etc.) to tuple. - HAPTER 2. STRING, LIST AND TUPLE 41 For Examples: go> t = tuple('1upins') po> print (t) fay, ws (PP, 4, me, tas) p> ti = tuple([1, 2, 3, ‘Python’, ‘Panda']) po> print (tl) (1, 2. 3, "Python", *Panda') Most of the list operations are also work on tuples 2.3.2 Index operator As similar to other sequence types, the index operator t(é) display the ith member of a tuple(indexing first member to 0). Consider tuple, >>>t=(‘al,’b’, 'c’, x’, 'y’, ’2!) Indexing as follows: ti) i Consider tuple: >>> t1[0] >>> ti[-1] tat >>> ti [2] ‘a >>> ti[-4) a 2.3.3 Slice operator 4 similar to string and list, the part of a tuple can be extracted using the slicing operation. Indexing \sing t{a : b] extracts elements t[a] to t[b..1]. A slice is used to pick out part of a string. Consider tuple, >> ts Car >> tla:ay > "Dt, tet, fat, te) SS CHAPTER 2. STRING, LIST AND TUPLE >>> tli] (bt, te") >>> tlt] e >>> t[:3) CE URSEL yCS5) ‘The tuples are immutable, if you try to modify one of the elements of the tuple, you get >>> t= (at, >>> to] = ta" ‘cl, » fe") Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Example 2.15. Copy element 44 and 55 from the following tuple into a new tuple >>> tuplel = (11, 22, 33, 44, 55, 66) We define new tuple using slice operator, >>> tuplel = (11, 22, 33, 44, 55, 66) >>> tuple2-tuplet [3:5] >>> tuple2 (44, 58) Example 2.16. Sort a tuple of tuples by ascending onder. >>> tuplet = (44, 11, 66, 22, 33, 55) First we convert tuple into list, then apply sorted() function then again convert into tuple. >>> tuplel = (44, 11, 66, 22, 33, 55) >>> tuple(sorted(list (tuplel))) (11, 22, 33, 44, 55, 66) 2.3.4 Tuple assignment ‘Tuples are usefull to assign values to multiple variables at instance. For examples to assign = 2, y = 4 and z = >>> (xy 2) = (24,9) Or CHAPTER 2. STRING, LIST AND Tupy 43. poe 622249 pe x, y= 3, 8 ‘22? XY = K+ Ky >>> print (x,y) 11-8 The number of variables on the left and the Tumber of values on the right have to be the same, otherwise you will get an error: >a, b= 4, 2, 3 Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 2) Example 2.17. Swap the following tuo tuples >>> tuplet = (11, 22) >>> tupie2 = (99, 83) >>> tuplet = (11, 22) >>> tuple2 = (99, 88) > tuplet, tuple2 = tuple2, tuplet >>> tuplet (99, ga) >> tuplez (41, 29) Example 2.18. Unpack the following tuple into 4 variables > atwpie = (10, 20, 30, 40) » > aTuple = (10, 20, 30, 40) » » Coyzwy) = aTuple >> x 10 sy = CHAPTER 2, STRING, LIST AND TUPLE ry 20 >> 2 30 >> w 40 2.3.5 Tuple as a return value Any function can only return one value, but ifthe value is a tuple, then it can return multiple values ‘The built-in function divmod() takes two arguments and returns a tuple of two values, the quotient and remainder. >>> divmod(7, 3) (2,1) ‘We can use tuple assignment to store the elements separately: >>> quot, rem = divmod(7, 3) >>> print quot 2 >>> print rem 1 Here is an example of a function that returns a tuple: >>> def min-max(t): return inin(t), max(t) In above programme max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values, Example 2.19. Write aPython programm using tuple that swap the values of two variable. >>> det swap(x,y): mY > ox return x, y >>> >>> x=q >>> ye? >>> swap(x,y) 7,4) HAPTER 2. STRING, LIST AND TUPLE 2.4 Exercise 1, Given the initial stateme s1- spam” s2-ni!” Show the result of evaluating each of the following string expressions, a) "The Knights who say, "+59 b) Sea1+2¥82 ©) sift] d) s1[1:3) e) si{2]+s2[:2] f) si+s2[-1] g) st.upper() h) s2.upper() .1just(4)*3 2. Two lists are given: 11=[1,2,3,4,5) 1Ea'y bt, tet ta? tet) Show the result of evaluating each of the following string expressions. a) 11[4] b) 12f:3] ©) 14[2:]+120:3] 4) 11+12[-1] 8) lisia £) Lowa } Two tuples are given Hecns sys jim, bt, 820 CR taste) Show the result of evaluating each of the following string expressions CHAPTER 2. STRING, LIST AND TUPLE d) ti+t2[-1] e) tist2 £) 202 4, Write a Python program to count the number of characters (character frequency) in 5, Write a Python program to get a string made of the first 2 and the last 2 chars from @ given string. 6. Write a Python function that takes a list of words and returns the length of the longest one 7. Write a Python program to change a given string to anew string where the first and la have been exchanged. 9, Write a Python program to reverse a tuple. 10. Write a Python program to find the length of a tuple. 11, Write a Python program to check whether an element exists within a tuple. 12. Write a Python program to sum all the items in a list. lies all the items in a list. 13. Write a Python program to mul 14, Write a Python program to get the largest number from a lis.

You might also like