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

Chapter 5 Theory

Uploaded by

jhavidya563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 5 Theory

Uploaded by

jhavidya563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Matrix Computers (Page 1 of 12)

10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan


9414752750, 9414930104, 9414244351, 0141-2399633

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.

Multi Line String:-


s1='''Multi
li\tne
str\ning'''
print(s1)

Output:-
Multi
li ne
str
ing

No character datatype in python just like C:-


type(‘a’) #<class str>

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

String object is iterable:-


for i in "hello":
print(i)

String supports ordering:-


"abc"=="acb" #False

String supports indexing and negative indexing also:-


s1 = 'matrix'
print(s1[0]) #m
print(s1[-1]) #x
print(s1[6]) #string index out of range
for i in range(0,len(s1)):
print(s1[i])

for i in range(len(s1)-1,-1,-1):
print(s1[i])

for i in range(-1,-len(s1)-1,-1):
print(s1[i])

String supports slicing:-


s1[start:stop:step] start is inclusive, stop is exclusive

-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

Q1. WAP to check whether a string is palindrome or not.

String object is immutable but its reference is mutable:-


s1='Hello'
s1='matrix' #allowed
s1[0]='z' #Not allowed
del s[1] #Not allowed
s1="abc"
del s1 #allowed

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.
>
<=
>=
==
!=

String Formatting Operator %:-


s1="Sum of %d and %d is %d" % (5,6,11)
print(s1)

s1=f"Sum of {a} and {b} is {a+b}"

s1="Sum of {} and {} is {}".format(a,b,a+b)

Format Symbol Conversion


%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

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.)

Built-in global functions:-


1 len(str) Returns the length of the string
2 max(str) Returns the max alphabetical character from the string str.
3 min(str) Returns the min alphabetical character from the string str.
4 ord(char) Return ascii of the character passed.
5 chr(int) Return character of the ascii value passed.
6 sorted(str) Returns a list of characters sorted in increasing order
sorted(str,reverse=True)
Returns a list of characters sorted in decreasing order.
7. bytearray() It returns a bytearray object and can convert objects into bytearray
objects, or create an empty bytearray object of the specified size.
bytearray([97,98,99]) #bytearray(b'abc')
s1="abcde"
b1=bytearray(s1,'utf8')
for i in b1:
print(i)
97,98,99,100,101
8. ascii() It returns a string containing a printable representation of an object and
escapes the non-ASCII characters in the string using \x, \u or \U escapes.
ascii('abc\nxy')-> 'abc\\nxy'

Str class methods:-


Sr.No. Methods with Description

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

Removes all trailing whitespace of string.

18 find(str, beg=0, end=len(string))


Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.

19 index(str, beg=0, end=len(string))


Same as find(), but raises an exception if str not found.

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

21 rindex( str, beg=0, end=len(string))


Same as index(), but search backwards in string.
WAP to count all the occurrences of a substring into a string.

22 replace(old, new [, max])


Replaces all occurrences of old in string with new or at most max occurrences if max
given.
s1="abababababab"
s1.replace("ab","xy") #'xyxyxyxyxyxy'
s1.replace("ab","xy",2) #'xyxyabababab'

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"]

s1="how are you"


print(s1.split()) #["how","are","you"]

s1="how are you"


print(s1.split(" ")) #["how","","are","","","you"]

"how are you mat".split(maxsplit=2)


Matrix Computers (Page 9 of 12)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

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'

31 count(str, beg= 0,end=len(string))(case sensitive)


Counts how many times str occurs in string or in a substring of string if starting
index beg and ending index end are given.

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.

33 endswith(suffix, beg=0, end=len(string))


Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with suffix; 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

It will convert str object to bytes class object


s1="abc"
s2=s1.encode()
type(s2) #<class 'bytes'>
for i in s1: #a
print(i) #b
#c
for i in s2: #97
print(i) #98
#99

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'

"Sum of {0} and {} is {}".format(5,6,11) #error


"Sum of {} and {} is {}".format(5,6) #error
"Sum of {0} and {0} is {1}".format(5,10) #Sum of 5 and 5 is 10
"Sum of {} and {} is {}".format(5,6,11,12) #Sum of 5 and 6 is 11

"Sum of {0} and {0} is {1}".format(5,10) #'Sum of 5 and 5 is 10'


l=[5,6,11]
"Sum of {0[0]} and {0[1]} is {0[2]}".format(l) #'Sum of 5 and 6 is 11'
"Sum of {} and {} is {}".format(*l) #'Sum of 5 and 6 is 11'
{:<d}.format(25)
{:<o}.format(25)
{:<b}.format(25)
{:<x}.format(25)
{:<10d}.format(25) #'25 '
{:>10d}.format(25) #' 25'
{:^10d}.format(25) #' 25'
{:+<10d}.format(25) #'25++++++++'
{:.2f}.format(25.55555) #'25.55'
{:10.2f}.format(25.55555) #' 25.55'
{:010.2f}.format(25.55555) #'0000025.55'
{0:o}.format(25) #31
{0:#o}.format(25) #0o31

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy