You are on page 1of 43

Python Strings

Computer Science 083


8

© Department of Computer Science, DPS R.K.Puram, New Delhi


Distribution of Marks and Periods 2

© Department of Computer Science, DPS R.K.Puram, New Delhi


Unit Unit Name Marks Periods
No. Theory Practical
1. Computer Systems and Organisation 10 10 5
2. Computational Thinking and Programming 45 50 35
3. Society, Law and Ethics - 1 15 20 --
Total 70 80 40
Unit II: Computational Thinking and Programming – 1 3

TERM - I

© Department of Computer Science, DPS R.K.Puram, New Delhi


● Strings: introduction, indexing, string operations (concatenation, repetition,
membership & slicing), traversing a string using loops, built-in functions:
len(), capitalize(), title(), lower(), upper(), count(), find(), index(),
endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(),
isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
String 4

String - It is a immutable type in Python. It is a collection of ASCII/Unicode

© Department of Computer Science, DPS R.K.Puram, New Delhi


characters. Its content are represented within a set of single or double quotes.

Assignment:
Name='Amar Shah'
City="Hyderabad"
Place="King's Palace"
Title='The Dream of "Doll" uncovered'
print(Name,"Lived in the", Place,"at", City)
print("His best book was entitled as",Title)
Amar Shah Lived in the King's Palace at Hyderabad
His best book was entitled as The Dream of "Doll" uncovered
String - Traversal 5

Txt="PEACE4LIFE"

© Department of Computer Science, DPS R.K.Puram, New Delhi


L=len(Txt)
print(Txt[0],"#",Txt[5])
for I in Txt:
print(I,end="*")
print()
OUTPUT
for i in range(L): P # 4
print(Txt[i],end="@") P*E*A*C*E*4*L*I*F*E*
print() P@E@A@C@E@4@L@I@F@E@
String - Concatenation 6

T1="STOP"

© Department of Computer Science, DPS R.K.Puram, New Delhi


T2="LOOK"
T3="GO"
T=T1+T2
OUTPUT
print(T)
STOPLOOK
print(T2+"&"+T3) LOOK&GO
String - Repetition 7

Msg="Hello"

© Department of Computer Science, DPS R.K.Puram, New Delhi


Dash='-'
Echo=Msg*3
Dashes=5*Dash*3
print(Dashes) OUTPUT
---------------
print(Echo) HelloHelloHello
print(Dashes) ---------------
String - Membership You can 8
search for
# Find me out this Symbol OUTPUT
on Google as

© Department of Computer Science, DPS R.K.Puram, New Delhi


TXT="MY CAR IN THE BOX" Guess Word:MY
Times=0;Score=0 Thumbs Up 👍
while True: Symbol Guess Word:CAR
WRD=input("Guess Word:") 👍
if WRD in TXT: Guess Word:BOX
Score+=1 👍
print("👍") in is a Guess Word:FIAT
membership Guess Word:THE
Times+=1
operator 👍
if Times>5:
Guess Word:IN
break
👍
print("Your Score:",Score,"/",Times) Your Score: 5 /5
len(), capitalize(), title(), upper(), lower() methods 9

len() to find number of characters in a string

© Department of Computer Science, DPS R.K.Puram, New Delhi


capitalize() to return case of the very first letter in upper case and
remaining in small
title() to return the case of first letter of every word to
uppercase and remaining in small
upper() to return the case of all the letters of the string into
upper case
lower() to return the case of all the letters of the string into
lower case
len(), capitalize(), title(), upper(), lower() methods 10

TXT="peace and soul"

© Department of Computer Science, DPS R.K.Puram, New Delhi


print(TXT.capitalize()) OUTPUT
print(TXT.title())
print(TXT.lower()) Peace and soul
print(TXT.upper()) Peace And Soul
for i in range(len(TXT)): peace and soul
if TXT[i] != " ": PEACE AND SOUL
print(TXT[i],end="*") p*e*a*c*e*
else: a*n*d*
print() s*o*u*l*
count() method 11

count() method searches the substring in a given string and returns how many

© Department of Computer Science, DPS R.K.Puram, New Delhi


times the substring is present in it.

It also takes two optional parameters start and end to specify the starting and
ending positions within the string.

The syntax of count() method with string is as follows:

<String>.count(<Substring>,<Start>,<End+1>)

Optional, if not specified, Optional, if not specified, length of


0 is considered string is considered
count() method 12

TXT="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


N=TXT.count("EL")
print("'EL' found",N,"TIMES") OUTPUT
N=TXT.count("EL",5) 'EL' found 2 TIMES
print("'EL' found",N,"TIMES") 'EL' found 1 TIMES
'EL' found 0 TIMES
N=TXT.count("EL",3,8) 4 TIMES
print("'EL' found",N,"TIMES")
print(TXT.count("E"),"TIMES")
find() method 13

find() method returns the index of first occurrence of a substring inside a string if

© Department of Computer Science, DPS R.K.Puram, New Delhi


it is found. If not found, it returns -1.

It also takes two optional parameters start and end to specify the starting and
ending positions within the string.

The syntax of find() method with string is as follows:

<String>.find(<Substring>,<Start>,<End+1>)

Optional, if not specified, Optional, if not specified, length of


0 is considered string is considered
find() method 14

TXT="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


N=TXT.find("EL") OUTPUT
print("'EL' found at",N) 'EL' found at 1
N=TXT.find("EL",5) 'EL' found at 12
print("'EL' found at",N) 'EL' found at -1
At 1
N=TXT.find("EL",3,8)
print("'EL' found at",N)
print("At",TXT.find("E"))
index() method 15

index() method returns the index of the first occurrence of a substring inside a

© Department of Computer Science, DPS R.K.Puram, New Delhi


string if it is found. If not found, it raises an exception (error).

It also takes two optional parameters start and end to specify the starting and
ending positions within the string.

The syntax of index() method with string is as follows:

<String>.index(<Substring>,<Start>,<End+1>)

Optional, if not specified, Optional, if not specified, length of


0 is considered string is considered
index() method 16

TXT="BELIEVE IN SELF" OUTPUT

© Department of Computer Science, DPS R.K.Puram, New Delhi


N=TXT.index("EL")
print("'EL' found at",N) 'EL' found at 1
'EL' found at 12
N=TXT.index("EL",5)
At 1
print("'EL' found at",N)
print("At",TXT.index("E")) --------------------------
N=TXT.index("EL",3,8) ValueError
print("'EL' found at",N)
Difference - index() and find() 17

index() find()

© Department of Computer Science, DPS R.K.Puram, New Delhi


A function/method A function/method

Returns the index of the first Returns the index of the first
occurrence of a substring inside a occurrence of a substring inside a
string, if it is found. string if it is found.

If the index is not found, it raises If the index is not found, it returns
an exception (error). -1.
startswith() 18

Msg1 = "Hello, how are you?"

© Department of Computer Science, DPS R.K.Puram, New Delhi


Msg2 = "India is a big country"
M1 = Msg1.startswith("Hello")
M2 = Msg2.startswith("Nepal")
OUTPUT
M3 = Msg1.startswith("Bye")
M4 = Msg2.startswith("India")
print(M1,M2) True False
print(M3,M4) False True
endswith() 19

Msg1 = "I am going to enjoy"

© Department of Computer Science, DPS R.K.Puram, New Delhi


Msg2 = "the football match"
M1 = Msg1.endswith("joy")
M2 = Msg2.endswith("match")
OUTPUT
M3 = Msg1.endswith("to")
M4 = Msg2.endswith("ball")
print(M1,M2) True True
print(M3,M4) False False
String - isalnum(), islower(), isupper(), isspace(), isalpha(), isdigit() 20

Methods

© Department of Computer Science, DPS R.K.Puram, New Delhi


isalnum() To check if string contains only alphabets/digits or not
isspace() To check if string contains only space(s) or not
isalpha() To check if string contains only alphabets or not
isdigit() To check if string contains only digits or not

islower() To check if string contains at least one lowercase letter and no


uppercase at all. Any alphabet from ‘a’ to ‘z’
isupper() To check if string contains at least one uppercase letter and no
lower case at all. Any alphabet from ‘A’ to ‘Z’
String - isalnum(), islower(), isupper(), isspace(), isalpha(), isdigit() 21

T1="Num 23";T2="car24"
T3="AMAZING";T4="end"

© Department of Computer Science, DPS R.K.Puram, New Delhi


T5=" ";T6="7392"
print(T1.isspace(),T1.isdigit(),T1.isupper(),T1.isalpha())
print(T2.isalnum(),T2.islower(),T2.isdigit())
print(T3.isupper(),T3.isalpha(),T3.islower())
print(T4.isupper(),T4.isalpha(),T4.islower())
print(T5.isspace(),T5.isalpha(),T5.islower())
print(T6.isdigit(),T6.isalpha())
OUTPUT
False False False False
True True False
True True False
False True True
True False False
True False
String - join() [Example 1] 22

Join all items in a string, a tuple or a list into a string, using a separator string.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Code="CLR" OUTPUT
Decode ="O".join(Code) Coded Message: CLR
print("Coded Message:",Code) Decoded Message: COLOR
print("Decoded Message:",Decode)

OUTPUT
Code="MLYLM" Coded Message: MLYLM
Decode ="A".join(Code) Decoded Message:
print("Coded Message:",Code) MALAYALAM
print("Decoded Message:",Decode)
String - join() [Example 2] 23

Join all items in a string, a tuple or a list into a string, using a separator string.

© Department of Computer Science, DPS R.K.Puram, New Delhi


SHORT="PPG" OUTPUT
PLACE ="AD".join(SHORT)+"ANJ"
SHORT NAME: PPG
print("SHORT NAME:",SHORT)
LONG NAME: PADPADGANJ
print("LONG NAME:",PLACE)

OUTPUT
FL="HD" FIRST LAST: HD
NM ="YDERABA".join(FL) FULL NAME : HYDERABAD
print("FIRST LAST:",FL)
print("FULL NAME :",NM)
String - join() [Example 3] 24

Join all items in a string, a tuple or a list into a string, using a separator string.

© Department of Computer Science, DPS R.K.Puram, New Delhi


FRIENDS=("AMAR","AKBAR","ANTHONY") OUTPUT
TOGETHER="".join(FRIENDS)
AMARAKBARANTHONY
print(TOGETHER)

OUTPUT
FRIENDS=("AMAR","AKBAR","ANTHONY") AMAR & AKBAR & ANTHONY
TOGETHER=" & ".join(FRIENDS)
print(TOGETHER)

tuple data type will be discussed in detail later. At present, you just need to know that it is
comma separated collection of elements (of any type) enclosed inside set of round braces ()
String - join() [Example 4] 25

Join all items in a string, a tuple or a list into a string, using a separator string.

© Department of Computer Science, DPS R.K.Puram, New Delhi


OUTPUT
FRIENDS=["AMAR","AKBAR","ANTHONY"]
TOGETHER="".join(FRIENDS) AMARAKBARANTHONY
print(TOGETHER)

OUTPUT
FRIENDS=["AMAR","AKBAR","ANTHONY"] AMAR & AKBAR & ANTHONY
TOGETHER=" & ".join(FRIENDS)
print(TOGETHER)

list data type will be discussed in detail later. At present, you just need to know that it is
comma separated collection of elements (of any type) enclosed inside set of square braces []
String - join() [Example 5] 26

Join all items in a string, a tuple or a list into a string, using a separator string.

© Department of Computer Science, DPS R.K.Puram, New Delhi


OUTPUT
A=[1,2,"A"]
B="".join(A) TypeError: sequence item 0: expected
print(B) str instance, int found

NOTE: Please note all the items are required to be of the type string and it
returns string type only

list data type will be discussed in detail later. At present, you just need to know that it is comma
separated collection of elements (of any type) enclosed inside set of square braces []
String - split() 27

Method

© Department of Computer Science, DPS R.K.Puram, New Delhi


split() It returns a list of substrings after breaking the given string with a
given separator.

<List>=<Str>.split(<Separator>[,<Maxsplit>])
Separator : String splits at this specified <Separator>. space is the default
separator.

Maxsplit : A number, to split the string into maximum of provided number of


times. If not provided then there is no limit.
String - split() 28

T="BELIEVE IN SELF" OUTPUT

© Department of Computer Science, DPS R.K.Puram, New Delhi


# Splits at space
print(T.split()) ['BELIEVE', 'IN', 'SELF']
print(T.split('L')) ['BE', 'IEVE IN SE', 'F']
print(T.split('E')) ['B', 'LI', 'V', ' IN S', 'LF']
print(T.split(' IN ')) ['BELIEVE', 'SELF']
String - split() 29

T="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


# Splits at space
print(T.split()) ['BELIEVE', 'IN', 'SELF']

print(T.split(' ',0)) ['BELIEVE IN SELF']


print(T.split(' ',1)) ['BELIEVE', 'IN SELF']
print(T.split(' ',2)) ['BELIEVE', 'IN', 'SELF']
print(T.split(' ',3)) ['BELIEVE', 'IN', 'SELF']
String - split() 30

T="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


# Splits at 'L'
print(T.split('L')) ['BE', 'IEVE IN SE', 'F']

print(T.split('L',0)) ['BELIEVE IN SELF']


print(T.split('L',1)) ['BE', 'IEVE IN SELF']
print(T.split('L',2)) ['BE', 'IEVE IN SE', 'F']
print(T.split('L',3)) ['BE', 'IEVE IN SE', 'F']
String - partition() 31

Method

© Department of Computer Science, DPS R.K.Puram, New Delhi


partition() To search for a specified string, and split the main string into a tuple
containing three elements.

<Tuple>=<Str>.partition(<Partition String>)

Partition String : A string that will partition the Str into three parts in a tuple.
String - partition() - Example 1 32

T="BELIEVE IN SELF"
OUTPUT

© Department of Computer Science, DPS R.K.Puram, New Delhi


# 'IN ' part of T
print(T.partition('IN ')) ('BELIEVE ', 'IN ', 'SELF')
# 'NOT' not part of T
print(T.partition('NOT ')) ('BELIEVE IN SELF', '', '')
# 'EL' part of T
# only first occurrence
print(T.partition('EL')) ('B', 'EL', 'IEVE IN SELF')
String - partition() - Example 2 33

OUTPUT
P="PEACE ON EARTH"

© Department of Computer Science, DPS R.K.Puram, New Delhi


print(P.partition(' ON ')) ('PEACE', ' ON ', 'EARTH')
print(P.partition('MOON')) ('PEACE ON EARTH', '', '')
print(P.partition('PEACE')) ('', 'PEACE', ' ON EARTH')
print(P.partition('E')) ('P', 'E', 'ACE ON EARTH')
print(P.partition('H')) ('PEACE ON EART', 'H', '')
String - strip(), lstrip(), rstrip() 34

Methods

© Department of Computer Science, DPS R.K.Puram, New Delhi


strip() To remove leading (spaces at the beginning) and trailing (spaces at
the end) characters. Space is the default leading character to remove

lstrip() To remove leading (spaces at the beginning) characters. Space is the


default leading character to remove

rstrip() To remove trailing (spaces at the end) characters. Space is the


default leading character to remove.

<Var>=<str>.strip(<Character>)
String - strip(), lstrip(), rstrip() 35

T=" BELIEVE IN SELF " OUTPUT

© Department of Computer Science, DPS R.K.Puram, New Delhi


print("#",T.strip(),"#") # BELIEVE IN SELF #
print("#",T.lstrip(),"#")
# BELIEVE IN SELF #
print("#",T.rstrip(),"#")
# BELIEVE IN SELF #
T="***BELIEVE IN SELF**"
print("#",T.strip("*"),"#") # BELIEVE IN SELF #
print("#",T.lstrip("*"),"#") # BELIEVE IN SELF** #
print("#",T.rstrip("*"),"#") # ***BELIEVE IN SELF #
String - replace() 36

Method

© Department of Computer Science, DPS R.K.Puram, New Delhi


replace() To replace a portion <Old> of string with another <New>. The third
parameter is optional as Count or number of occurrences to be replaced. If
the third parameter not specified, it will replace all the occurrence of <Old>
with <New>

<New Str>=<Str>.replace(<Old>,<New>,[<Count>])
String - replace() - Example 1 37

T="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


S1=T.replace("SELF","YOURSELF")
print(S1)
S2=S1.replace("YOURSELF","YOUR SELF")
print(S2)
S3=T + " " + S2
print(S3)
S4=S3.replace("BELIEVE","TRUST")
print(S4)
S5=S3.replace("BELIEVE","TRUST",1)
print(S5)
BELIEVE IN YOURSELF
BELIEVE IN YOUR SELF
BELIEVE IN SELF BELIEVE IN YOUR SELF
TRUST IN SELF TRUST IN YOUR SELF
TRUST IN SELF BELIEVE IN YOUR SELF
String - replace() - Example 2 38

S1="20 IS MINE"

© Department of Computer Science, DPS R.K.Puram, New Delhi


S1=S1.replace("IS","ARE")
print(S1)
S2=S1.replace("0","51")
print(S2)
S2=S2.replace("MINE","YOURS")
S3=S1 + " & " + S2
print(S3)
S4=S3.replace(" "," - ")
print(S4) 20 ARE MINE
251 ARE MINE
20 ARE MINE & 251 ARE YOURS
20 - ARE - MINE - & - 251 - ARE - YOURS
String - String Slicing 39

String slicing helps in extracting a portion of a string with the help of

© Department of Computer Science, DPS R.K.Puram, New Delhi


indexes.

<String>[<Start Index>:<End Index+1>:<Step>]

Default Values - Start Index (Beginning of string) End Index (End of string)

<String>[::<+ve step>]

Default Values - Start Index (End of string) End Index (Beginning of string)

<String>[::<-ve Step>]
String - Slicing 40
OUTPUT
T="BELIEVE IN SELF"

© Department of Computer Science, DPS R.K.Puram, New Delhi


print(T[0:3]) BEL
print(T[4]) E
print(T[2:]) LIEVE IN SELF
print(T[:9]) BELIEVE I
print(T[::-1]) FLES NI EVEILEB
print(T[1:13:2]) EIV NS
print(T[::]) BELIEVE IN SELF
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
T B E L I E V E I N S E L F
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String - Slicing 41

N="0123456789"
OUTPUT

© Department of Computer Science, DPS R.K.Puram, New Delhi


print(N)
0123456789
print(N[-1:-5:-1])
9876
print(N[6:1:2])
print(N[2:8:3])
25
print(N[:6:2])
024
print(N[7::-2])
7531
print(N[:9:4])
048
print(N[-5:-3])
56

0 1 2 3 4 5 6 7 8 9
N 0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
To do - “More with strings” 42

● To count and display “No. of times” of presence of words “the” and “to” in a

© Department of Computer Science, DPS R.K.Puram, New Delhi


string. (should not count words like these and top)
● To count and display the words ending with ‘y’ or ‘i’ in a string.
● To display content of each word in reverse order from a string.
● To display all those words, which contain "tion" in it.
● To count those words, which start with a Vowel,
● To display those words, which have two consecutive vowels in a string
● To display all those words, which have more than two characters, display the
content in a single line.
● To find those words in a string, which are palindrome.
● To encode the string by displaying the next alphabet of each alphabet (out
of next in sequence of the character set). Example: "THE BOY" will be "UIF
CPZ"
Note: Use can use - ord() and chr()functions in this code.
43

© Department of Computer Science, DPS R.K.Puram, New Delhi


Thank you!
Department of Computer Science
Delhi Public School R.K.Puram New Delhi

You might also like