Python Jyoti Chandnani
Composite Datatypes or Collections or Data Structures
Python supports different types of data structures:
1. String
2. List
3. Tuple
4. Set
5. Dictionary
STRING DATA STRUCTURE
1. A sequence of characters is called String.
2. Python supports str data type to represent string type data.
3. String objects are immutable objects that mean we can’t modify the existing string object.
4. Insertion order is preserved in string objects.
5. A string allows multiple duplicate characters also.
6. Every character in the string object is represented with unique index.
7. Python supports both forward and backward indexes.
8. Forward index starts with 0 and negative index starts with -1.
9. Python string supports both concatenation and multiplication of string objects.
10. Strings can be created by enclosing characters inside a single quote or double quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.
Eg: creating a string with single quote
>>> name='Jyoti' >>> print(name) ➔
Eg: creating a string with double quotes
>>> name="Jyoti" >>> print(name)➔
Eg: creating a string with triple quotes
>>> name='''Jyoti''' >>> print(name) ➔
(or)
>>> name="""Jyoti""" >>> print(name) ➔
Using triple quotes for multiple line comments
>>>name="""Hello, Welcome to
world of PYTHON.
Working With PYTHON is very fun."""
>>>print(name)
➔Hello, Welcome to
world of PYTHON.
Working With PYTHON is very fun.
1. We can access individual characters using indexing and a range of characters using slicing.
2. Index starts from 0. If we try to access a character out of index range then interpreter will raise
an IndexError.
3. The index must be an integer. If we try to access the data with non-integer indexes values then
interpreter raises TypeError.
1
Python Jyoti Chandnani
String Indexing : It is nothing but fetching a specific character by using its index number.
Eg:
>>> x='JYOTI' >>> print(x)➔ JYOTI
Indexing
0 1 2 3 4
J Y O T I
-5 -4 -3 -2 -1
Forward index
>>> print (x[0])➔ J
>>> print (x[4]) ➔ I
Backward index: Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
>>> print (x[-1])➔ I
>>> print (x[-5]) ➔J
If we modify the content of the existing object then the indexes also will be changed
Eg:
>>> x=" Jyoti" ➔ Index- 0 to 5
Eg2:
>>> st1="Python Jyoti"
>>> st1[6] ' ' #space is treated as empty character
>>> st1[15] string index out of range
>>> st1[-16] IndexError: string index out of range
we should use only integers as index numbers,if we try to use then interpreter will return TypeError,
using float numbers:
>>> st1[1.5]
>>> st1['a']
>>> st1[2+5j]
All above examples will give TypeError: string indices must be integers but we can use bool values(True or
False) as index numbers, because python treats True as 1 and False
as 0 using bool values
>>> st1[True] 'y'
>>> st1[False] 'P'
String slicing:
We can access a range of characters using slicing.
The slicing operator is colon (:)
Eg:
>>> a='JYOTI'
>>> print(a[0:1])
>>> print(a[0:2])
>>> print(a[0:5])
>>> print(a[2:5])
>>> print(a[4:5])
2
Python Jyoti Chandnani
Eg2:
>>> st[:]
>>> st[::]
>>> st[4:]
>>> st[:4]
>>> st[:-6]
>>> st[-10:]
>>> st[-10:10]
>>> st[-20:20]
Syn: st[starting_number::step_size] st= “Python Jyoti”
>>> st[1::2] 'yhnJoi' #from 1,it takes all 2 multiple characters, like y,h,n,J,o,i.
>>> st[-10::3] #from -10, it takes all 3 multiple characters, in forward indexing because 3 is +ve
>>> st[-9::3] #from -9,it takes all 3 multiples, in forward indexing because 3 is +ve number
>>> st[-15::2] #from -15, it takes all 2 multiple characters in forward indexing because 2 is +ve number
>>> st[10::-2] 10 means 'a' and negative index -5, it takes all -2 multiples in backward indexing from -5
>>> st[13::-2] 13 means n and negative index is -2, it takes all -2 multiples in backward indexing from -2
>>> st[::-2] here starting index number is not specified so here interpreter takes from last character
onwards, that is 12, and negative index number is -1, so from -1 it takes all -2 multiples in
backward indexing.
>>> st[::-1]
here also starting index is not specified so it takes from last character onwards, that is 12, and negative
index number is -1, so from -1 it takes all -1 multiples in backward indexing, so finally it takes all characters
from ending to beginning.. that means it displays the given string in reverse order
>>> st[-True::-3]
it works as above example, -True means -1
String Concatenation:
1. We can concatenate two or more strings into a single string is called concatenation.
2. The + operator is used in Python for concatenation.
Eg:
>>> string1='Python'
>>> string2='Developer'
>>> print('String1 + string2 :', string1+' '+string2)
String Multiplication:
1. Python supports multiplying or repeating the given string into n number of times.
2. The * operator can be used to repeat the string for a given number of times.
Eg:
>>> string1='Python'
>>> print(string1 * 3)➔
String is immutable object because we cannot replace or alter the existing string object.
Eg:
>>> st='Python'
>>> print(st)
>>> st=st+'s' #altering the string object
>>> print(st)
3
Python Jyoti Chandnani
Id is changed to before modification and after modification of the string st. that’s why string is a
immutable object.
Here when we try to edit the existing string object(st in 42221792), then the new object (st in
41200640) is created.
String packing:
Its nothing but packing all values of defined variables as a single string
>>> a='x'
>>> b='y'
>>> c='z'
>>> st=''.join([a,b,c])
>>> print(st)➔ xyz
>>> type(st) <class 'str'>
String unpacking
1. String unpacking allows extracting all characters of string into different variables automatically.
2. The number of variables must be equal to number of characters in the string.
>>> str1="Python"
>>> print(str1)
>>> type(str1) <class 'str'>
>>> a,b,c,d,e,f=str1 #string unpacking
>>> print(a)
>>> type(a) <class 'str'>
>>> print(b)
>>> type(b) <class 'str'>
>>> print(c)
>>> type(c) <class 'str'>
>>> print(d)
>>> type(d) <class 'str'>
>>> print(e)
>>> type(e) <class 'str'>
>>> print(f)
>>> type(f) <class 'str'>
We can not update the existing characters of the string with new characters,
Eg:
>>> st="python"
>>> print(st) python
>>> type(st) <class 'str'>
>>> st[0]='X' TypeError: 'str' object does not support item assignment
4
Python Jyoti Chandnani
String Functions:
1. Capitalize(): this function converts first letter of first word in the given string into upper case.
Eg1:
>>> str1='python developer'
>>> [Link]()
Eg2:
>>> st1='1python 2developer'
>>> [Link]()
Eg3:
>>> st2='@gmail'
>>> [Link]()
Eg4:
>>> st3='gmail'
>>> [Link]()
Eg5:
>>> st4=' python Jyoti'
>>> [Link]()
2. Title(): this function converts first character of each word in the given string into upper case.
Eg1:
>>> str1='python developer'
>>> [Link]() 'Python Developer'
Eg2:
>>> st1='1python 2developer'
>>> [Link]() '1Python 2Developer'
Eg3:
>>> st2='@gmail'
>>> [Link]() '@Gmail'
Eg4:
>>> st3='_python developer'
>>> [Link]() '_Python Developer'
Eg5:
>>> st4=' python Jyoti'
>>> [Link]() ' Python Jyoti'
3. Islower(): this function checks whether the given string contains all lower case letters or not. If all
are lower case then it will return True else False.
Eg1:
>>> str1='python developer'
>>> [Link]()
Eg2:
>>> str2="Python"
>>> [Link]()
Eg3:
>>> st=' '
>>> [Link]() False
Eg4:
>>> str3='PYthon DEVEloper'
>>> [Link]() False
5
Python Jyoti Chandnani
4. isupper():this function checks whether the given string contains all upper case letters or not. If all
are upper case then it will return True else False.
Eg1:
>>> str1='python developer'
>>> [Link]()
Eg2:
>>> str3='PYTHON'
>>> [Link]()
Eg3:
>>> st=' '
>>> [Link]() False
Eg4:
>>> str3='PYthon DEVEloper'
>>> [Link]()
5. lower(): this function converts all letters of given string into lower case.
Eg1:
>>> str3='PYTHON'
>>> [Link]() 'python'
Eg2:
>>> str3='PYthon DEVEloper'
>>> [Link]() 'python developer'
6. upper():this function converts all letters of given string into upper case.
Eg1:
>>> str1='python developer'
>>> [Link]() 'PYTHON DEVELOPER'
Eg2:
>>> str3='PYthon DEVEloper'
>>> [Link]() 'PYTHON DEVELOPER'
7. len(): this function counts the number of characters in the given string.
>>> str1='python developer'
>>> len(str1)
8. count() : this function counts [Link] occurrences of a specific character in the given string.
Eg1:
>>> str1='python developer'
>>> [Link]('o')
Eg2:
>>> str3='python developer tcs hyd'
>>> [Link](' ')
9. find(): this function finds the index position of specific character in the given string.
Eg1:
>>> str1='python developer'
>>> [Link]('o') 4 ---for first occurrence of ‘o’
>>> [Link]('o',5) 12 ---for second occurrence of ‘o’
Eg2:
>>> str3='python developer tcs hyd'
6
Python Jyoti Chandnani
>>> [Link](' ') 6
>>> [Link](' ',7) 16
>>> [Link](' ',17) 20
>>> [Link](' ',21) ValueError: substring not found
10. split(): this function splits the given strings into multiple strings
Eg1:
>>> str1='python developer'
>>> [Link]() ['python', 'developer']
Note: the default delimiter is space.
Eg2:
>>> str2='python developer in TCS'
>>> [Link]() ['python', 'developer', 'in', 'TCS']
Eg3:
>>> str3='[Link]'
>>> [Link]('.') ['python', 'developer', 'in', 'TCS']
Eg4:
>>> str4='developer'
>>> [Link]('l') ['deve', 'oper']
Eg5:
st='''Hello Renu,
Hope you doing fine,,
How is your python language preparation?
You should learn DJANGO Framework as well,
so that you will get more calls.
Thanks,
Python Jyoti,
Python Trainer.
'''
>>> Print([Link](‘\n’))
['Hello Renu,', 'Hope you doing fine,,', 'How is your python language preparation?', 'You should
learn DJANGO Framework as well,', 'so that you will get more calls.', '', 'Thanks,', 'Python
Jyoti,', 'Python Trainer.', '']
>>> [Link](' ')
['Hello', 'Renu,\nHope', 'you', 'doing', 'fine,,\nHow', 'is', 'your', 'python', 'language',
'preparation?\nYou', 'should', 'learn', 'DJANGO', 'Framework', 'as', 'well,\nso', 'that', 'you', 'will',
'get', 'more', 'calls.\n\nThanks,\nPython', 'Jyoti,\nPython', 'Trainer.\n']
11. lstrip(): this function removes specific special character to left side of given string.
str1='!!!!!!Python Developer!!!!!!!'
>>> [Link]('!') 'Python Developer!!!!!!!'
12. rstrip(): this function removes specific special character to the right side of given string
str1='!!!!!!Python Developer!!!!!!!'
>>> [Link]('!') '!!!!!!Python Developer'
[Link](): this function removes specific special character from both sides to the given string.
str1='!!!!!!Python Developer!!!!!!!'
>>> [Link]('!') 'Python Developer'
7
Python Jyoti Chandnani
[Link](): This function swaps all lower case letters into upper case and vice versa.
Eg1:
>>> str1='PyThOn'
>>> [Link]() 'pYtHoN'
Eg2:
>>> str2='PYTHON DEVELOPER'
>>> [Link]() 'python developer'
Eg3:
>>> str3='python developer'
>>> [Link]() 'PYTHON DEVELOPER'
[Link](): this function reverses the string
>>> str='Python'
>>> print(str) Python
>>> str=''.join(reversed(str))
>>> print(str) nohtyP
15. replace(): this function replaces an existing character(s) with new character(s).
Eg1:
>>> str1='python learner'
>>> print(str1) python learner
>>> str2=[Link]('learner','developer')
>>> print(str2) python developer
Eg2:
>>> st1='SQL Jyoti'
>>> st1=[Link]('SQL','Python')
>>> print(st1) Python Jyoti
Note: we can remove any character(s) with non-empty space.
>>> str1='Python'
>>> print(str1) Python
>>> type(str1) <class 'str'>
>>> str2=[Link]('thon','')
>>> print(str2) Py
>>> type(str2) <class 'str'>
16. del command:
we cant delete a specific character or range of characters by using del command.
We can delete the entire string objects permanently by using del command
Eg 1:
>>> str1="Python Jyoti" #trying to remove specific character
>>> del str1[0] TypeError: 'str' object doesn't support item deletion
Eg 2:
>>> str1="Python Jyoti" #trying to remove specific range of characters
>>> del str1[1:5] TypeError: 'str' object does not support item deletion
Eg 3:
>>> str1="Python Jyoti"
>>> print(str1)
8
Python Jyoti Chandnani
>>> type(str1) <class 'str'>
>>> del str1 #deleting entire string str1 object
>>> print(str1) #after deleting
NameError: name 'str1' is not defined
17. rjust(), ljust():
The rjust() and ljust() string methods return a padded version of the string they are called on, with
spaces inserted to justify the text. The first argument to both methods is an integer length for the
justified string.
>>> 'python'.rjust(10)➔
>>> 'python'.rjust(15) ➔
>>> 'python'.ljust(10) ➔
>>> 'python'.ljust(15) ➔
>>> 'Hello Python'.rjust(20) ➔
>>> 'Hello Python'.ljust(20) ➔
'python'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10. 'python' is six
characters, so four spaces will be added to its left, giving us a string of 10 characters with 'python'
justified right.
An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
>>> 'python'.rjust(10,'*')
'****python'
>>> 'python'.rjust(15,'@')
'@@@@@@@@@python'
>>> 'python'.ljust(10,'*')
'python****'
>>> 'python'.ljust(15,'*')
'python*********'
>>> 'Hello Python'.rjust(20,'!')
'!!!!!!!!Hello Python'
>>> 'Hello Python'.ljust(20,'!')
'Hello Python!!!!!!!!'
18. Center()
The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.
>>> 'python'.center(10)
' python '
>>> 'python'.center(15)
' python '
>>> 'python Jyoti'.center(20)
' python Jyoti '
>>> 'python'.center(10,'*')
'**python**'
>>> 'python'.center(15,'*')
'*****python****'
>>> 'python Jyoti'.center(20,'*')
'**python Jyoti***'
>>> "Hello".center(20,'=')
9
Python Jyoti Chandnani
'=======Hello========'
These methods are maily useful when we need to print tabular data that has the correct spacing.
How to display the given string in ascending order?
>>> st="python"
>>> ''.join(sorted(st)) 'hnopty'
>>> st1="PyThON deVELoPer" #if string contains both upper and lower cases
>>> ''.join(sorted(st1))
19. The join() method is useful when we have a list of strings that need to be joined together into a single
string value. The join() method is called on a string, gets passed a list of strings, and returns a string. The
returned string is the concatenation of each string in the passed-in list.
How to display the given string in descending order?
>>> st="python"
>>> ''.join(reversed(sorted((st)))) 'ytponh'
How to display the given string with two dots between
each character.
>>> s1='python'
>>> s10='..'.join(s1)
>>> s10
How to display the given string with space between each
character.
>>> st='Jyoti'
>>> st=' '.join(st)
>>> print(st)
20. By using ::
>>> st='python Jyoti'
>>> st[::]
>>> st[0::]
>>> st[1::]
>>> st[0::1]
>>> st[1::0] ValueError: slice step cannot be zero
>>> st[1::1]
>>> st[2::1]
>>> st[6::1
>>> st[6::2]
>>> st[0::-4]
10
Python Jyoti Chandnani
String comparison
Eg1:
st1='b'
st2='a'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output
b is bigger than a
Note: in the above program, we have set st1=’b’ and st2=’a’ when we see the alphabet in ascending
order( from a to z), then here, ‘b’ is bigger than ‘a’
Eg2:
st1='a'
st2='b'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
Eg3:
st1='a'
st2='a'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
11
Python Jyoti Chandnani
Eg4:
st1='bc'
st2='ax'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
Note: interpreter will check only first characters from both strings, so as per first characters, st1 is
bigger than st2.
Eg5:
st1='ax'
st2='am'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
Eg6:
st1='python'
st2='Jyoti'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
Note: ‘p’ in the st1 is bigger than ‘n’ in the st2 string. So st1 variable value is bigger than st2 variable
value.
12
Python Jyoti Chandnani
Eg7:
st1='1ax'
st2='am'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output
am is bigger than 1ax
Note: here interpreter compares ‘1’ from st1 with ‘a’ from st2 variable.
Generally characters are bigger than numbers, so st2 variable value is bigger than st1 variable value.
Eg8:
st1='2ax'
st2='2am'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output
Note: in the above example, first two characters are same from both strings, now interpreter decides
based on third character. ‘x’ is bigger then ‘m’, so st1 variable value bigger than st2 variable value.
Eg9:
st1='123'
st2='a123'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output :
13
Python Jyoti Chandnani
Eg10:
st1='ax'
st2='*m'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output:
Note: in the above example, characters are bigger than special characters. So here ‘a’ is bigger than ‘a’.
Eg11:
st1='1x'
st2='&am'
if st1>st2:
print(st1,'is bigger than',st2)
elif st2>st1:
print(st2,'is bigger than',st1)
else:
print('both',st1,'and',st2,'are equal')
Output
Note: in the above program, interpreter compares ‘1’ from st1 with ‘&’ from st2 .
Generally integers are bigger than special characters
14