Python Session 12 Strings
Python Session 12 Strings
Data types
Type cast
Basic codes
Modules pacakges
conditional
functions
for loop
while loop
- list : 60-40
- Tuple : 100
- dictionary
- sets
- lambda functions
- file handling
In built functions
type
min
max
len
sum
sorted
reversed
Concatenation
Index
Mutable/Immutable
Slice
Methods
In [5]: str1='python'
str2="python"
str3='i like "python"'
str4="i like 'python'"
str5="""
hello
how are you
"""
In [9]: print(str1)
python
inbuilt functions
In [16]: type(str1)
print(str1)
len(str1)
python
Out[16]: 6
In [ ]: type()
len()
print()
min()
max()
sum()
sorted()
reversed()
In [18]: str1='apple'
str2='123456'
str3='apple123'
In [22]: print(len(str1))
print(len(str2))
print(len(str3))
5
6
8
In [24]: print(min(str1))
print(min(str2))
print(min(str3))
a
1
1
In [26]: print(max(str1))
print(max(str2))
print(max(str3))
p
6
p
In [ ]: len,min,max
In [28]: sum(str1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[28], line 1
----> 1 sum(str1)
In [30]: print(str2)
sum(str2)
123456
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 2
1 print(str2)
----> 2 sum(str2)
In [32]: print(str3)
sum(str3)
apple123
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[32], line 2
1 print(str3)
----> 2 sum(str3)
In [34]: 10+'a'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[34], line 1
----> 1 10+'a'
In [ ]: sum('apple')
0+'a'
In [36]: 0+'a'+'p'
Out[36]: 'ap'
In [ ]: sum('apple')
In [ ]: def f(a,/,b):
print(a+b)
f(10,20) # w
f(a=10,b=20) # n
f(10,b=20) # w
In [3]: str1='python'
#sorted(iterable, /, *, key=None, reverse=False)
# iterable: anything can be loop
# anything we can print using loop
# for i in 'python'
# print(i)
# strings ,list,tuple,dict all are consider are iterable objects
sorted()
In [5]: print('python')
print([10,20,30])
python
[10, 20, 30]
In [7]: type('python'),type([10])
In [ ]: min()
max()
len()
type()
print()
In [ ]: str1='python'
#sorted(iterable, /, *, key=None, reverse=False)
sorted('python') # works
sorted(iterable='python') # notworks
In [9]: str1='python'
sorted('python')
# by default ascending order
# there is a possibility i can make descending order
In [11]: str1='python'
print(sorted('python')) # ascending
print(sorted('python',reverse=True)) # descening
reversed
In [15]: str1='python'
reversed(str1)
3
2
1
n
o
h
t
y
p
In [21]: str1='python123'
# list type cast
list(reversed(str1)) # int() eval()
Out[21]: ['3', '2', '1', 'n', 'o', 'h', 't', 'y', 'p']
In [ ]: 5am
6am to 7.15am
7.30am to 9am
9am to 10.30am : login
10.30 to 12pm : attend
12.30 -- 1pm : class upload
1pm to 1.30pm
1.30pm to 5pm office
5.30pm to 7pm : class
7pm to 8.30pm : class
9pm
9pm to 10pm 12am 1am
In [ ]: type()
len()
print()
min()
max()
sum()
reversed()
sorted()
# l=[10,20,30,40,50]
# l=['Apple','Ball','Cat']
# l=[10,20,30,40,'Apple','Ball','Cat']
Conactenation
In [ ]: str1='hello'
str2='good morning'
str1+str2
str1*str2
str1-str2
str1/str2
In [24]: str1='hello'
str2='good morning'
str1+str2
In [26]: str1-str2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[26], line 1
----> 1 str1-str2
In [28]: str1/str2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[28], line 1
----> 1 str1/str2
In [30]: str1*str2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 1
----> 1 str1*str2
In [32]: str1='hello'
str1*2 # can multiply sequence by int
Out[32]: 'hellohello'
In [ ]: 2*2: 2+2
'hello'*2 = 'hello'+'hello'
index
In [35]: str1='python'
In [ ]: -6 -5 -4 -3 -2 -1
p y t h o n
0 1 2 3 4 5
index is used to access the letters
In [48]: str1='python'
str1[0],str1[1],str1[2],str1[3],str1[4],str1[5]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[50], line 1
----> 1 str1[6]
In [ ]: str1='python'
str1[0]
str1[1]
str1[2]
str1[3]
str1[4]
str1[5]
str1[i] i in range(0,6)
In [56]: # -6 -5 -4 -3 -2 -1
# p y t h o n
# 0 1 2 3 4 5
# 0 to -6
# 1 to -5
# 2 to -4
# i to i-6
# 0 to 0-6
# 1 to 1-6
for i in range(0,6):
print(i,str1[i],i-6)
0 p -6
1 y -5
2 t -4
3 h -3
4 o -2
5 n -1
In [68]: str1='python'
for i in range(len(str1)):
print(str1[i])
p
y
t
h
o
n
In [70]: str1='python'
for i in str1:
print(i)
p
y
t
h
o
n
1.using index
2.Direct access
i in str1
In [ ]: # wap ask the user find the number of 'a' in a given string
# str1='ola ola ola' ans=3
# wap ask the user find the indexes of 'a' in a given string
# str1='ola ola ola' 2 6 10
# wap ask the user find the sum of the indexes of 'a' in a given string
# str1='ola ola ola' 2 +6 +10=18
In [75]: # wap ask the user find the number of 'a' in a given string
# str1='ola ola ola' ans=3
str1='ola ola ola'
count=0
for i in str1:
if i=='a':
count=count+1
count
Out[75]: 3
2 a
6 a
10 a
Out[81]: 3
2 a
6 a
10 a
Out[83]: (3, 18)
In [9]: # wap ask the user find the vowels in a given string
# str1='ola ola ola' o a o a o a
o
a
o
a
o
a
o
a
Mutable-Immutable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[22], line 2
1 str1='welcome' # ====> 'weLcome'
----> 2 str1[2]='L'
In [27]: l=[10,20,30,40]
l[2]=300
l
Out[27]: [10, 20, 300, 40]
Slice
Out[32]: 'ihwae'
Out[34]: ''
Out[38]: 'yeawh'
Out[52]: 'yeawh'
In [ ]: - intilaization
- concat
- slice
In [ ]: str1='python'
list1=[10,20,30,40,50,60]
list2=['A','B','C','D']
list3=[10,20,30,40,50,60,'A','B','C','D']
len(list1)
len(list2)
len(list3)
sum(list1),sum(list2),sum(list3)
max(list1),max(list2),max(list3)
min(list1),min(list2),min(list3)
sorted(list1),sorted(list2),sorted(list3)
reversed(list1),reversed(list2),reversed(list3)
list1+list2
for i in list1:
print(i)
In [68]: list1=[10,20,30,40,50,60]
list2=['A','B','C','D']
list3=[10,20,30,40,50,60,'A','B','C','D']
len(list1)
str1='python'
len(str1)
Out[68]: 6
In [ ]: sum('python')
sum(['p','y','t','h','o','n'])
max([10,'A']) # error
sorted([10,'A']) # comaprining two diff data types
Methods
In [ ]: type()
print()
min()
max()
sorted()
reversed() these all are inbuilt functions
this not only for string
other data types list
Out[4]: 2
In [6]: dir('')
dir('python')
str1='hello'
dir(str1)
Out[6]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
upper
In [9]: str1='python'
str1.upper()
Out[9]: 'PYTHON'
lower
title
capitalize
center
startswith/endswith
lstrip/rstrip/strip
In [27]: str1='python' # 6
# str1.center(width, fillchar=' ', /)
str2=str1.center(10,'*')
str2,len(str2)
In [ ]: str1.upper() # upper(str1) X
str1.lower() # lower(str1) X
str1.title() # title(str1) X
str1.capitalize()
str1.center(10,'*')
In [ ]: 'python'.upper() # upper(str1) X
'PYTHON'.lower() # lower(str1) X
'hai How Are you'.title() # title(str1) X
'hai how are you'.capitalize()
'python'.center(10,'*')
In [29]: 'python'.center(6,'*')
Out[29]: 'python'
startswith
Out[54]: True
In [62]: #h a i h o w a r e y o u
#0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
str1='hai how are you'
##str1.startswith(prefix,start,end)
str1.startswith('h') # 'hai how are you'
str1.startswith('h',4) # 'how are you'
str1.startswith('o',4,10) # 'how ar'
Out[62]: False
Out[64]: True
In [72]: #h a i h o w a r e y o u
#0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
str1='hai how are you'
#str1.endswith(suffix,start,end)
str1.endswith('u',4) # str1[4:] : how are you
str1.endswith('o',4,10) # str1[4:10] : how ar
Out[72]: False
strip
count
Out[96]: 3
In [100… sorted('python')
Out[106… 0
Out[112… 1
In [114… str1.count('ola')
Out[114… 3
Upper/Lower/Casefold
title/capitalize
startswith/endswith (char,start,end)
count (sub,start,end)
replace
we already know strings are immutable
In [6]: str1='welcome'
# output : 'weLcome'
#str1.replace(old, new, count=-1)
str1.replace('l','L')
Out[6]: 'weLcome'
In [8]: # Return a copy with all occurrences of substring old replaced by new.
str1='welcome welcome'
str1.replace('l','L')
In [ ]: str1='welcome'
str1.replace('l','L')
str1='welcome welcome'
str1.replace('l','L')
str1='welcome welcome'
str1.replace('l','L',1)
In [14]: str1='welcome'
str1.replace('z','L')
Out[14]: 'welcome'
index-find
Out[63]: 1
Out[69]: 13
Out[71]: 13
In [ ]:
i3=s.index('l',s.index('l',s.index('l') +1) +1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[79], line 7
5 i4=s.index('l',i3+1)
6 i5=s.index('l',i4+1)
----> 7 i6=s.index('l',i5+1)
8 i1,i2,i3,i4,i5
In [91]: s1='[email protected]'
s2='[email protected]'
s3='[email protected]'
first=s1.index('.')
secont=s1.index('.',first+1)
at=s1.index('@')
fname=s1[:first]
sname=s1[first+1:at]
cname=s1[at+1:secont]
cname
Out[91]: 'rcb'
In [93]: dir('')
Out[93]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
In [ ]: 'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
In [97]: 'Python'.istitle()
Out[97]: True
In [ ]: