Python Data Presistence – Methods of Built-in Data Type Classes

Python Data Persistence – Methods of Built-in Data Type Classes

Python built-in object of a certain type is characterized by attributes and methods, and as defined in the built-in class of the corresponding name. Methods defined in s tr class for example are available for use to each string object. So is the case of list, tuple, and dictionary objects.

In this section, some commonly used methods of built-in type classes are described. (Two new terms pop up here – class and methods. You’ll come to know about them in the chapter on Object-oriented programming. For the time being treat a method as a function only.)

String Methods

Various methods in str class fall into the following categories:

Related to Case of Alphabets

1. capitalize ( ): Method changes the first letter of the given string to uppercase and returns another string object.

Example

>>> str1=1 python string’
>>> str2=str1.capitalize( )
>>> str2
‘Python string’

2. lower ( ): Method returns a string object by replacing all alphabets in given string with respective lowercase equivalents.

Example

>>> str1=’Python String’
>>> str2=strl.lower( )
>>> str2
‘python string’

3. upper ( ): Method ensures that the resulting string consists of all uppercase alphabets.

Example

>>> str1=’Python String’
>>> str2=str1.upper()
>>> str2
‘PYTHON STRING’

4. title ( ): Method titlecases the string having first alphabet of each word in uppercase.

Example

>>> str1=’python string’
>>> str2=strl.title()
>>> str2
‘Python String’

5. swapcase ( ): Method replaces uppercase alphabets by lowercase and vice versa.

Example

>>> str1=’Simple is Better than Complex.’
>>> str2=str1.swapcase()
>>> str2
‘SIMPLE IS bETTER THAN COMPLEX.’
>>> str1=str2.swapcase()
>>> str1
‘Simple is Better than Complex.’

Find/Replace Methods

1. find( ): Method returns index of first occurrence of a substring in given string. If not found, the method returns -1

Example

>>> str1=’Simple is Better than Complex.’
>>> str1 .find (‘p1’ )
3
>>> strl .find (‘bet’ )
-1

2. index( ): Method is similar to find() except this one raises ValueError if the substring is not found.

Example

>>> str1=’Simple is Better than Complex.’
>>> str1. index (‘p1’ )
3
>>> strl.index(‘bet’)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: substring not found

3. replace ( ): Method requires two string parameters. All occurrences of first parameter get replaced by second parameter.

Example

>>> str1=’all animals are equal. Some are more equal
>>> str1.replace(‘are’, ‘were’)
‘all animals were equal. Some were more equal’

4. count( ): Method returns an integer corresponding to the number of times a substring occurs in a given string.

Example

>>> str1=’Simple is Better than Complex.’
>>> str1.count(‘pi1)
2

Methods Returning Boolean Result

1. isalpha ( ): Method returns True if all characters in given string are alphabetic i.e a-z or A-Z.

Example 

>>> str1=’BpbOnline’
>>> str1.isalpha()
True
>>> str2=’BPB Publications’
>>> str2.isalpha()
False

2. isdigit ( ): Method returns True if the string is made of all digits. If not, it returns False.

Example

>>> str1= ‘8860322236’
>>> str1.isdigit ( )
True
>>> str1= ‘ (+91) 8860322236’
>>> str1 . isdigit ( )
False

3. islower( ) : If all alphabets in given string are in lowercase,this method returns True otherwise returns False.

Example

>>> str1=’pythonrocks’
>>> str1.is lower( )
True

4. isupper ( ): Method returns True if all alphabets in given string are in uppercase not considering other characters.

Example

>>> str1=’IIT JEE’
>>> str1.isupper( )
True

5. startswith( ): method returns True if the given string has substring parameter or any of string items is in a tuple parameter. If it doesn’t, then False is returned.

Example

>>> name=1 Mr. John’
>>> name.startswith(‘Mr’)
True
>>> name=’Dr. Watson’
>>> name.startswith((‘Mr’ , True ‘Dr’))
True

6. endswith ( ): Method checks whether the substring parameter is at the end of a given string and returns True if so, otherwise returns False. The substring to be checked can also be in the tuple parameter.

Example

>>> name=’Mr. John’
>>> name.endswith(‘on’)
False
>>> name=’Dr. Watson’
>>> name.endswith((‘on’, True 1 ‘hn’))
True

Join/split

1. join( ): Method concatenates all string objects in a list or tuple. Items in list/tuple are separated by given string object.

>>> list1= [‘Python’, 1 C++’, ‘Ruby’, 1Kotlin’]
>>> sep=’ and ‘
>>> sep.join(list1)
‘Python and C++ and Ruby and Kotlin’
>>> listl= [‘192’, ‘168’, ‘0’ , ‘1’ ]
>>> sep=’.’
>>> sep.join(listl)
‘192.168.0.1’

2. split ( ): Method separates splits given string into parts wherever the substring parameter is found. The parts are returned in the form of a list object.

Example

>>> str1=’all animals are equal. Some are more equal’
>>> strl.split(‘ ‘)
[‘all’, ‘animals’, ‘are’, ‘equal.’, ‘Some’, ‘are’, ‘more’, ‘equal’]
>>> strl=’192.168.0.1′
>>> strl.split(‘.’)
[ ‘ 192’, ‘ 168’, ‘O’, ‘1’ ]

3. strip ( ): If no parameter is present in the parentheses of this method, then leading and trailing spaces are removed. The parameter can be a string of one or more characters. It acts as a set of characters to be removed.

Example

>>> str1=’ Hello Python ‘
>>> strl.strip( )
‘Hello Python’
>>> str1=’all animals ‘are equal’
>>> str1.strip(‘alu’)
‘ animals are eq’

4. format( ): Method returns a formatted string by interpolating placeholders in the given string by values of objects. Values of parameters in the method’s parentheses fillup the place holders marked by {}.

Example

>>> name=’Virat Kohli’
>>> runs=10385
>>> print (‘{ } is Captain of India. He has scored {} runs in ODI.’.format(name,runs))
Virat Kohli is Captain of India. He has scored 10385 runs in ODI.

The curly bracket placeholders in the string are filled in the same order in which parameters appear in parentheses. You can also refer to the parameter by name and use them in any order.

Example

>>> name=’Virat Kohli’
>>> runs=10385
>>> print (‘{nm} is Captain of India. He has scored {r} runs in ODI.1.format(r=runs,nm=name))
Virat Kohli is Captain of India. He has scored 10385 runs in ODI.

Python also supports C-style string formatting using the ‘ %’ sign as a substitution character. The format specification symbols (like %d, %f, %c, and so on; famously used in print( ) statement of C program) are available for use in Python too.

Example

>>> name=1Virat Kohli’
>>> runs=10385
>>> print (“%s is Captain of India. He has scored %d runs in ODI.” % (name,runs))
Virat Kohli is Captain of India. He has scored 10385 runs in ODI.

List Methods

As described earlier, the list is a mutable data type. It means, it is possible to change the contents of a list object after it has been defined. In this section, you will learn to handle methods in list class that can add/modify/rein o ve items in a list object.

1. append ( ): Method adds a new item at the end of the given list.

Example

>>> list1=[‘Python’,’C++’ ’Ruby’, Kotlin’]
>>> list1.append(‘JS’)
>>> list1
[‘Python’, ‘C++’, ‘Ruby’, ‘Kotlin , ‘JS’]
>>>

2. insert ( ): Method needs two parameters. the Second parameter is the new object to be added. The first parameter is the index at which it will be inserted. Again, the sequence index starts from 0.

Example

>>> list1=[‘Python’,’C++’ ‘Ruby’ ‘Kotlin’]
>>> list1.insert(2,’Java’)
>>> list1
[‘Python’, ‘C++’, ‘Java’, ‘Ruby’ ‘Kotlin’]
>>>

3 . count ( ): Method returns an integer corresponding to number of times a certain item appears in given list.

Example

>>> list1= [3,5,9,3,6]
>>> list1.count(3)
2
>>> str1=’all animals are equal. Some are more equal’
>>> list1=strl.split(‘ ‘)
>>> list1
[‘all’, ‘animals’, ‘are’, ‘equal.’, ‘Some’, ‘are’, ‘more’, ‘equal’]
>>> list1.count(‘are’)
2
> > >

4. index ( ): method returns the index of the first occurrence of a certain value if found in a given list. If it is not found, then the method raises ValueError.

Example

>>> list1= [‘ all’ , ‘animals’, ‘are’, ‘equal.’, ‘Some’, ‘are’, ‘more’, ‘equal’]
>>> list1.index(‘are’)
2
>>> listl.index(‘were’)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: ‘were’ is not in list
>>>

5 . reverse ( ): Order of items in given list is reversed by using this

>>> list1=[‘Python’, ‘C++ , ‘Ruby’, ‘ Kotlin’, 1 JS’ ]
> > > listl.reverse( )
> > > list1
[ ‘ JS ‘, ‘Kotlin’, ‘Ruby’, C++’, ‘Python’]
> > >

6 . sort ( ): Items in the given list object are rearranged in ascending order unless the method’s ‘reverse’ parameter set to True.

Example

>>> list1= [‘Python’, ‘C++’, ‘Ruby’, ‘Kotlin’, ‘JS’]
>>> list1.sort()
>>> list1
[‘C++’, ‘JS’, ‘Kotlin’, ‘Python’, ‘Ruby’]
>>> list2= [‘all’, ‘animals’, ‘are’, ‘equal.’,
‘Some’, ‘are’, ‘more’, ‘equal’]
>>> list2.sort(reverse=True)
>>> list2
[‘more’, ‘equal.’, ‘equal’, ‘are’, ‘are’, ‘animals’, ‘all’, ‘Some’]
> > >

7. remove ( ): Method causes removal of an item’s first occurrence from the given list. If the item to be removed is not found in the list, then ValueError is raised.

Example

8 . pop ( ): Method is similar to remove() method. However, this method returns the removed item. The pop( ) method by default removes the last item in the list. If it contains an index parameter, the item at the specified index is removed and returned.

Example

>>> list1= [‘Python’, ‘C++’, ‘Ruby’, ‘Kotlin’, ‘JS’]
>>>lang=list1.pop( )
>>>>>> list1.sort( )
>>> list1
[‘C++’, ‘JS’, ‘Kotlin’, ‘Python’, ‘Ruby’]
>>> list2= [‘all’, ‘animals’, ‘are’, ‘equal.’,
‘Some’, ‘are’, ‘more’, ‘equal’]
>>> list2.sort(reverse=True)
>>> list2
[‘more’, ‘equal.’, ‘equal’, ‘are’, ‘are’, ‘animals’,
‘all’, ‘Some’] ‘
> > >

If you remember, a tuple is an immutable object. As a result, the above methods performing addition, removal, sorting, and so on; can’t be used with tuple. Only count ( ) and index ( ) methods are available for a tuple object. Their behavior is similar to list methods of the same name.

Dictionary Methods

Like List, a dictionary object is also mutable. However, the dictionary is not a sequence. Its items do not have an index. So, index-based insertion or removal is not supported. Following methods are defined in the built-in dictionary class:

1. get ( ): Method retrieves value component corresponding to key parameter.

Example

>>> dict1 = {‘Mumbai 1 :’Maharashtra’, ‘Hyderabad’:’Telangana’, ‘Patna1:’Bihar’}
>>> dict1.get(‘Patna’)
‘Bihar’
>>>

2. pop ( ): Method removes k-v pair item from given dictionary object corresponding to key parameter, an returns its value component.

Example

>>> dict1 = {1 Mumbai’: Maharashtra’ , ‘Hyderabad’:’Telangana’, ‘Patna’:’Bihar’}
>>> state=dictl.pop( ‘Mumbai’)
>>> state
‘Maharashtra’
>>>

3 . popitem ( ): Method returns a k-v pair in the form of a tuple.

Example

>>> dictl={‘Mumbai’:’Maharashtra’,
‘Hyderabad’:1Telangana’, ‘Patna’:’Bihar’}
>>> t=dictl.popitem()
>>> t
(‘Patna’, ‘Bihar’)
>>>

4. update ( ): Method is used to add a new k-v pair item as well as modify the value of the existing key. The update() method takes another • dictionary object as a parameter. There may be one or more items in it. If its key is not used in a given dictionary, a new k-v pair is added. If the key is already present, its value is replaced by the new value. This process takes place for all items in the diet parameter.
In following code snippet, dictl is updated by adding a new state- capital pair.

Example

>>> dict1={‘MaharashtraBombay’Andhra Pradesh1:1 Hyderabad’, ‘UP’ :’Lucknow’}
>>> dict1.update({‘MP’ :’Bhopal1})
>>> dict1
{‘Maharashtra’: ‘Bombay’, ‘Andhra Pradesh’: ‘Hyderabad’, ‘UP’: ‘Lucknow’, ‘MP’: ‘Bhopal’}
>>>

The initial dictionary object gets updated by another diet parameter. Capitals of two states are modified and one pair is added.

Example

>>> dict1={‘Maharashtra’: ‘Bombay’, ‘Andhra Pradesh’: ‘Hyderabad’, ‘UP’: ‘Lucknow’, ‘MP’: ‘Bhopal’}
>>> dict2={‘AndhraPradesh’:’Amaravati’,’Telangana’:’Hyderabad’, ‘Maharashtra’:’Mumbai’}
>>> dictl.update(dict2)
>>> dict1
{‘Maharashtra’: ‘Mumbai’, ‘Andhra Pradesh’: ‘Amaravati’, ‘UP’: ‘Lucknow’, ‘MP’: ‘Bhopal’, ‘Telangana’: ‘Hyderabad’}
>>>

You can also add a new k-v pair simply by assigning value to the unused key by the following syntax:

dict1[newkey]=value

Here is an example:

Example

>>> dict1 ={‘Maharashtra’: ‘Bombay’ , ‘Andhra Pradesh ‘ : ‘ Hyderabad ‘ , ‘ UP’ : ‘Lucknow’ , ‘MP’ , ‘Bhopal’}
>>> dict1 [‘Maharastra’] = ‘Mumbai’
>>> dict1
{‘Maharashtra’: ‘Bombay’ , ‘Andhra Pradesh ‘ : ‘ Hyderabad ‘ , ‘ UP’ : ‘Lucknow’ , ‘MP’ , ‘Bhopal’}
>>>

Dictionary View Methods

1. items ( ): Method returns a view object consisting of two-item tuples, one for each k-v pair. This view object can be converted to a list of k-v tuples.

Example

>>> dict1 = {‘Maharastra’: ‘Mumbai’ , “Andhra pradesh’ :’Amaravati’ , ‘UP’: ‘Lucknow’ , ‘MP’: ‘Bhopal’, ‘Telangana’ : ‘Hyderabad’}

>>> items=dict1.items( )

>>> items

dict_items([{‘Maharastra’ , ‘Mumbai’), (‘Andhra pradesh’ , ‘Amaravati’), (‘UP’, ‘Lucknow’), (‘MP’, ‘Bhopal’), (‘Telangana’ , ‘Hyderabad’}])

>>> list(items)

[(‘Maharastra’ , ‘Mumbai’), (‘Andhra pradesh’, ‘Amaravati’), (‘UP’, ‘Lucknow’), (‘MP’, ‘Bhopal’), (‘Telangana’ , ‘Hyderabad’}])

>>>

2.keys ( ):

The method returns a view object consisting of all keys in a given dictionary. This view object can be converted to a list of keys.

Example

>>> dict1 = {‘Maharastra’: ‘Mumbai’ , ‘Andhra pradesh’ :’Amaravati’ , ‘UP’: ‘Lucknow’ , ‘MP’: ‘Bhopal’, ‘Telangana’ : ‘Hyderabad’}

>>> keys=dict1.keys( )

>>> keys

dict_keys([‘Maharastra’ , ‘Andhra pradesh’ , ‘UP’ , ‘MP’ , ‘Telangana’])

>>> list (keys)

[‘Maharastra’ , ‘Andhra pradesh’ , ‘UP’ , ‘MP’ , ‘Telangana’]

>>>

3 . values ( ): Method returns a view object consisting of all values in a given dictionary. This view object can be converted to a list of values.

Example 

>>> dictl={1 Maharashtra’: ‘Mumbai’, ‘Andhra Pradesh’: ‘Amaravati’, ‘UP’: ‘Lucknow’, ‘MP’:
‘Bhopal’, ‘Telangana’: ‘Hyderabad’}
>>> values=dictl.values()
>>> values
dict_values([‘Mumbai’, ‘Amaravati’, ‘Lucknow’,
‘Bhopal’, ‘Hyderabad’])
>>> list(values)
[‘Mumbai’, ‘Amaravati’, ‘Lucknow’, ‘Bhopal’,
‘Hyderabad’3
>>>

All view objects returned by items(), keys(), and values() methods get automatically refreshed whenever the underlying dictionary object gets updated.

Example

>>> dictl={‘Maharashtra’:’Bombay’,’Andhra Pradesh’:
‘Hyderabad’, ‘UP’:’Lucknow’}
>>> items=dictl.items()
>>> keys=dictl.keys >>> values=dictl.values >>> items
dict_items([(‘Maharashtra’ , ‘Bombay’), (‘Andhra Pradesh’, ‘Hyderabad’), (‘UP’, ‘Lucknow’)])
>>> dict2={‘Andhra
Pradesh’:’Amaravati’,’Telangana’:’Hyderabad’,
‘Maharashtra’:’Mumbai’}
>>> dictl.update(dict2)
>>> items
dict_items([(‘Maharashtra’, ‘Mumbai’), (‘Andhra
Pradesh’, ‘Amaravati’), (‘UP’, ‘Lucknow’),
(1Telangana’, ‘Hyderabad’)])
>>>

We have thus reached the end of a fairly lengthy introductory chapter of this book. As mentioned in the preface, this (and next) chapter is intended to be a quick-start tutorial for Python. So try and explore Python as much as you can with Python’s interactive shell. The next chapter explains how Python’s scripting mode works. Python’s conditional and looping techniques are also discussed there.