Chapter 5 Theory
Chapter 5 Theory
Chapter 5 String
String is a collection of alphabets, digits and symbols. It can contains 0 or more characters.
There is no char datatype in python. In python string can be enclosed in single or double or triple
quotes. All strings are objects of class str.
Output:-
Multi
li ne
str
ing
Double quotes string can contain single quotes and single quotes string can contain double
quotes and triple quotes can contain both single and double quotes or we can also use escape
sequence also:-
" feet=5'. ", ' inches=6". ', ''' height is 5'6". '''
" feet=5\'. ",' inches=6\". ', ''' height is 5\'6\". '''
If two strings contain only alphabet and digits only then both strings will share same id but if it
contains space or symbols then python will create different objects:-
s1="matrix"
s2="matrix"
s1 is s2 #True
s1="matrix123"
s2="matrix123"
s1 is s2 #True
s1="abc xyz"
s2="abc xyz"
s1 is s2 #False
s1="abc@xy"
Matrix Computers (Page 2 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
s2="abc@xy"
s1 is s2 #False
for i in range(len(s1)-1,-1,-1):
print(s1[i])
for i in range(-1,-len(s1)-1,-1):
print(s1[i])
-6-5-4-3-2-1
s1="M A T R I X "
012345
print(s1[1:5]) #ATRI
print(s1[1:12]) #ATRIX No error out of range
print(s1[6:12]) # Empty string no index error
print(s1[:]) #MATRIX
print(s1[1:]) #ATRIX
print(s1[:4]) #MATR
print(s1[::]) #MATRIX
print(s1[::2]) #MTI
print(s1[5:1:]) # Empty string
print(s1[5:1:-1]) #XIRT
print(s1[::-1]) #XIRTAM
print(s1[-6:-1]) #MATRIX
Matrix Computers (Page 3 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Raw string:-
Suppresses actual meaning of Escape characters.
s1="abc\txy"
print(s1) #abc xy
s1=r"abc\txy"
Matrix Computers (Page 4 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
print(s1) #abc\txy
Operator Description
+ Concatenation
* Repetition
[] Slice Gives the character from the given index
[:] Range Slice - Gives the characters from the given range
in Membership - Returns true if a character exists in the given string
not in Membership - Returns true if a character does not exist in the given string
< Relational Operator compare character by character using ascii values.
>
<=
>=
==
!=
Other supported symbols and functionality are listed in the following table
Symbol Functionality
* argument specifies width or precision
Matrix Computers (Page 5 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
- left justification
+ display the sign
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether
'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
m.n. m is the minimum total width and n is the number of digits to display after the decimal
point (if appl.)
1 lower() or casefold()
Converts all uppercase letters in string to lowercase.
s1="MATRIX"
s1.lower() #matrix
s1.casefold() #matrix
str.lower(s1)
2 upper()
Converts lowercase letters in string to uppercase.
Matrix Computers (Page 6 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
s1="matrix"
s1.upper() #MATRIX
3 capitalize()
Capitalizes first letter of the first word of the string.
s1="how are you"
s1.capitalize() #How are you
4 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.
s1="how are you"
s1.title() #How Are You
5 swapcase()
Inverts case for all letters in string.
s1="MaTrIx"
s1.swapcase() #'mAtRiX'
6 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
s1="maTrix:
s.islower() #False
7 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
s1="MATRIX:
s.isupper() #True
8 istitle()
Returns true if string is properly "titlecased" and false otherwise.
s1="How Are You"
s1.istitle() #True
9 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
s1="abc123"
s1.isalpha() #False
Matrix Computers (Page 7 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
10 isdigit()
Returns true if string contains only digits and false otherwise.
s1="123"
s1.isdigit() #True
11 isnumeric()
Returns true if a string contains only digits and false otherwise.
s1="123"
s1.isnumeric() #True
12 isdecimal()
Returns true if a string contains only digits and false otherwise.
s1="123"
s1.isdecimal() #True
13 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.
s1="abc123"
s1.isalnum() #True
14 isspace()
Returns true if string contains only whitespace characters and false otherwise.
s1=" \t "
s1.isspace() #True
Q. WAP to input a line and count lower, upper, digits, alpha, spaces and symbols.
15 strip([chars])
Performs both lstrip() and rstrip() on string.
s1=" abc xyz "
s1.strip() #'abc xyz'
s1="ABABABabc xyzABABAB"
s1.strip("BA") #'abc xyz'
16 lstrip([chars])
Removes all leading whitespace in string.
s1=" hello world "
s1.lstrip() #hello world
s1="ABCCBAAAAhello worldABCCBAAAA"
s1.lstrip("ABC") #hello worldABCCBAAAA
17 rstrip([chars])
Matrix Computers (Page 8 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
20 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
s1="it is a is and is" (start<stop)(Left to right)
s1.rfind("is",7,16) #8
s1.rfind("is",7,17) #15
23 split([str])
Splits string according to delimiter str (space if not provided) and returns list of
substrings;
s1="how are you"
print(s1.split()) #["how","are","you"]
s1="howzzzarezzzyou"
print(s1.split("zzz")) #["how","are","you"]
a,b,c=input("Enter 3 strings").split()
a,b,c=map(int,input("Enter 3 integers").split())
a,b,c=map(float,input("Enter 3 floating numbers").split())
lst=list(map(int,input("Enter 3 integers").split()))
m=map(int,input("Enter 3 integers").split()) #map object
l=[1,2,3]
l2=list(map(str,l)) #['1','2','3']
l=['1','2','3']
l2=list(map(int,l)) #[1,2,3]
24 rsplit([str])
"how are you mat".rsplit(maxsplit=2)
s1="how are you matrix computers"
s1.split(maxsplit=3)
['how', 'are', 'you', 'matrix computers']
s1.rsplit(maxsplit=3)
['how are', 'you', 'matrix', 'computers']
s1.split()
['how', 'are', 'you', 'matrix', 'computers']
s1.rsplit()
['how', 'are', 'you', 'matrix', 'computers']
25 splitlines()
Splits string from NEWLINEs and returns a list of each line with NEWLINEs removed.
s1="abc\nxyz\nzzz"
s1.splitlines() #['abc', 'xyz', 'zzz']
s1.splitlines(keepends=True) #['abc\n', 'xyz\n', 'zzz']
26 join(iterable)
Only for strings. we can pass list or tuple or set of strings. If we pass a single string then it
will assume it as list of strings of one character each. Merges (concatenates) the string
representations of elements in sequence seq into a string, with separator string.
l1=["mat","rix"]
"".join(l1) #'matrix'
" ".join(l1) #'mat rix'
"...".join(l1) #'mat...rix'
"aaa".join("matrix") #'maaaaaaataaaraaaiaaax'
27 ljust(width[, fillchar])
Matrix Computers (Page 10 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Returns a space-padded string with the original string left-justified to a total of width
columns.
28 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width
columns.
s1="+5"
s1.rjust(10) #' +5'
29 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
columns.
30 zfill(width)
Just like rjust but always fill with 0. Returns original string leftpadded with zeros to a
total of width characters; intended for numbers, zfill() retains any sign given (less one
zero).
s1="matrix"
s1.zfill(20) #'00000000000000matrix'
s1="+5"
s1.zfill(10) #'+000000005'
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
34 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
s1="abc\txyz\tzzz"
s1.expandtabs() #'abc xyz zzz'
s1.expandtabs(20) #'abc xyz zzz'
35 encode()
Matrix Computers (Page 11 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
36 decode()
It will convert bytes class object to str object
s3=s2.decode()
37 "".isidentifier()
It will check whether the str object can be used as a identifier or not.
38 isprintable()
s1="abc\nxy\tzz"
s1.isprintable() #False
s1="abcxyzz"
s1.isprintable() #True
39 partition()
Always return 3 item tuple
s1="xyaxyaxyaxy"
s1.partition("a") #('xy', 'a', 'xyaxyaxy')
s1="matrix"
s1.partition("x") #('matri', 'x', '')
s1="matrix"
s1.partition("z") #('matrix', '', '')
40 rpartition()
s1="xyaxyaxyaxy"
s1.rpartition("a") #('xyaxyaxy', 'a', 'xy')
Q. WAP to input a floating number and print is decimal and fraction part seperately.
41 maketrans()
Matrix Computers (Page 12 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
42 translate()
s1="aeiou"
s2="12345"
s3="matrix computers"
d=s3.maketrans(s1,s2) #d={97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
s3.translate(d) #'m1tr3x c4mp5t2rs'
43 format()
{} are called as place holders
"Sum of {} and {} is {}".format(5,6,11)#'Sum of 5 and 6 is 11'
"Sum of {0} and {1} is {2}".format(5,6,11) #'Sum of 5 and 6 is 11'
for i in range(1,16):
print("{0:<10d} {0:<10b} {0:<10o} {0:<10x}".format(i))
{:,}.format(1234567) #1,234,567
d={"roll":101,"Name":"aryan"}
"{roll} {name}".format(**d) #101 Aryan
"{roll} {name}".format_map(d) #101 Aryan
"{roll} {name}".format(roll=101,name="Aryan") #101 Aryan