Chapter 5 Strings - CBSE
Chapter 5 Strings - CBSE
STRINGS IN PYTHON
Learning Objective:
CBSE Syllabus
The power of python lies in its one of very strong data type named strings.
Like many other popular programming languages, strings in Python are arrays of bytes
representing Unicode characters. However, Python does not have a character data
type, a single character is simply a string with a length of 1.
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
Strings can be created by enclosing characters inside a single quote or double quotes
and assigning to the variable. Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.
Python indexes its strings in two ways. One is forward indexing and other is backward
indexing. Let’s look at the below example to have better understanding of same.
Backward Indexing
Forward Indexing
First character H would start from 0 and last character’s index would be 11 while
accessing forwardly.
In backward accessing, first character H would be at index -12 and last character would
be at index -1.
Get the character at position 1 (remember that the first character has the
position 0):
Output
e
Output
10
a=input("enter a string:")
for i in range(-1,-3,-1):
print(a[i])
Output
enter a string : monika
a
k
Last position
Program 8: WAPS to print reverse of a string
a=input("enter a string")
for i in range(-1,-len(a)-1,-1):
print(a[i])
Output
enter a string: hello
o
l
l
e
h
j=0
a=input("enter a string")
for i in range(-1,-len(a)-1,-1):
print(a[j],'\t',a[i])
j+=1
Output
enter a string:hello
o
h l
e l
l e
l h
o
‘
Program: # WAPS to accept a main string and substring and check if the
substring is a part of the main string or not using in operator.
a=input("enter a main string")
b=input("enter a substring")
if(b in a):
print(b," is substring of ",a)
else:
print(b," is not substring of ",a)
Program : # WAPP to accept a main string and substring and check if
the substring is a part of the main string or not using not in
operator.
We can calculate the ordinal value of the string by adding the values of each character
in the string.
Lets consider the below given examples
‘a’ >’A’ As Ordinal Value of A is 65 whereas ordinal value of ‘a’ is 97
‘ABC’ > ‘AB’ As Ordinal Value of ‘ABC’ is more than ordinal value of ‘AB’
‘abc’ Will give false as ordinal value of ‘abc’ is 294 whereas ordinal value of
<=’ABCD’ ‘ABCD’ is 266.
‘abcd’>’abcD’ Will give true because of obvious reasons.
‘ab’>=’ab’ Will give true as >= means either greater than or equal to.
‘ab’<=’ab’ Will give true as <= means either less than or equal to.
FINDING ORDINAL VALUE OF SINGLE CHARACTER
Bulit In function ord( ) is used to find the ordinal value of a character in python.
Consider the example given below
ord( ) function is used for single character. It can’t be used for string
FINDING CHARACTER CORROSPONDING TO ORDINAL VALUE
Opposite of ord( ) is chr( ) function.chr( ) function returns the character corresponding to
the ordinal value. Consider the example given below.
String Manipulation
1. WAP to count the number of characters in an input string.
a=input("enter string")
c=0
for i in a:
c=c+1
print(c)
2. WAP to count the number of vowels in an input string.
c=0
str=input("Enter the string ")
for i in str:
if i in "aeiouAEIOU":
c=c+1
print(c)
3. WAP to input your name and print each character of your name in same
line with a space between.
4.WAPS to accept a main string and a substring and check if substring exists in
main string
8.WAP to replace all characters other than alphabets and numbers to space.
10.WAP that capitalizes every alternate letter of the user entered string.
s=0
name=input("enter a string: ")
for a in name:
if ord(a)>=48 and ord(a)<=57:
s=s+int(a)
print("The sum is",s)
13.WAP to enter a string and count the no of words , no of alpha numeric
characters and special characters.
w=0
x=0
s=0
a=input("enter string")
for i in range(0,len(a)):
if a[i]==' ':
w=w+1
if (ord(a[i])>=97 and ord(a[i])<=122) or (ord(a[i])>=65 and ord(a[i])<=90)
or (ord(a[i])>=48 and ord(a[i])<=57):
x=x+1
else:
s=s+1
print("the count of words is",w+1)
print("the count of alphanumeric characters is",x)
print("the count of special characters is",s)
14.WAP to enter a string and convert all upper case to lower case and viceversa.
a=input("enter string")
b=''
for i in range(0,len(a)):
if ord(a[i])>=65 and ord(a[i])<=90:
b=b+chr(ord(a[i])+32)
elif ord(a[i])>=97 and ord(a[i])<=122:
b=b+chr(ord(a[i])-32)
print(b)
15.WAP to keep on entering strings till user says ‘y’ and convert all upper case to
lower case and viceversa.
ans='yes'
while ans=='yes':
a=input("enter string")
b=''
for i in range(0,len(a)):
if ord(a[i])>=65 and ord(a[i])<=90:
b=b+chr(ord(a[i])+32)
elif ord(a[i])>=97 and ord(a[i])<=122:
b=b+chr(ord(a[i])-32)
print(b)
ans=input("do you want to continue or not")
16.#enter a string reverse the string
a=input("enter the string")
x=''
for i in range(len(a)-1,-1,-1):
x=x+a[i]
print(x)
Output
enter a string : malayalam
palindrome
c=0
name=input("enter a string: ")
for a in name:
if a=='a' or a=='e' or a=='i' or a=='o'or a=='u':
c+=1
print("The count of vowels is",c)
Output
enter a string: hello be here
The count of vowels is 5
egEGoVEGoREGo**CEGo
******************************************************************
0 1 2 3 4 5 6 7 8
G R A T I T U D E
-9 -8 -7 -6 -5 -4 -3 -2 -1
Word=”GRATITUDE”
word[0:9] Will print characters from subscript 0 to 9.Last subscript is not
‘GRATITUDE’ included.
word[0:7] Will print characters from subscript 0 to 6
‘GRATITU’
word[0:3] Will print characters from subscript 0 to 2
‘GRA’
word[2:5] Will print characters from subscript 2 to 5
‘ATI’
word[-9:-6] Will print characters -9,-8,-7.-6 will be excluded as last character is
‘GRA’ excluded.
word[-6:-2] Will print characters from subscript -6,-5,-4,-3.
‘TITU’
Remember, in string slice, character at the last index is not included in the
result.
In string slice, if the beginning index is missing, then python considers 0 as the
beginning index. If the last value is missing then python considers last value as length
of the string. Consider the example given below.
Word=”GRATITUDE”
word[:9] Will print characters from subscript 0 to 8.
‘GRATITUDE’
word[:3] Will print characters from subscript 0 to 2.
‘GRA’
word[3:] Will print characters from subscript 3 till last.
‘TITUDE’
word[2:5] Will print characters from subscript 2 to 4
‘ATI’
word[-9:] Will print characters from beginning till the end.
‘GRATITUDE’
word[:-6] Will print characters from beginning to the 3rd character
‘GRA’
(refer Diagram of string for better understanding)
Solved Questions
1. Question: Give the output of the following code
Ans
d) >>>p= “Program”
a)>>>“Program”[3:5] >>>p[4:]
b) >>>“Program”[3:6] e) >>>p= “Program”
c) >>>p= “Program” >>>p[3:6]
>>>p[:4]
a)’gr’ d)’ram’
b)’gra’ e)’gra’
Ans c)’Prog’
3. Give output of the following
a) len(“Amazing School”)
b) print(“Great” +” “+ “School”)
c) print(“A” * 4 )
d) pr” in “computer”
Ans a)14
b)Great School
c)AAAA
d)False
4 Give output
a="hello"
>>> print(a[0:0])
Ans It will print nothing.
>>>name1=' a '
>>>name1.lstrip()
'a '
Also lstrip() function is used to remove a leading characters from string when it is used
with arguments.
Let’s look at the examples for better understanding
>>> a='Hello There'
3.rstrip()
rstrip() method is used to remove right padded spaces in a given string when is used
without arguments.
>>>name1=' a '
>>>name1.rstrip()
' a'
When rstrip() function is used with arguments then it removes the characters mentioned
in the arguments from the right hand side.
a="Hello There"
>>>name1=' a '
>>>name1.strip()
'a'
However if the space is in the middle of string, it does nothing.
a="hello there"
>>> a.strip()
'hello there'
5.lower()
lower() method is used to convert given string in to lower case.
>>>name1="INDIA"
>>>name1.lower()
‘india’
6. upper()
upper() method is used to convert given string in to upper case.
name='india'
name.upper()
'INDIA'
7. title()
title() method is used to convert given string in to title case. Every first character of word of a
given string is converted to title case.
name="india is my country"
name.title()
'India Is My Country'
8.swapcase()
swapcase() method is used to toggle the case of characters. If the characters are
capital, they will be converted to lower case and vice versa.
>>>name1="MoNiKa"
>>>name1.swapcase()
'mOnIkA'
13.find() method
find() method is used to find the first occurrence of particular character or string in a
given string.
name="I love python"
>>> name.find('o')
3
It finds the first occurrence of ‘o’ which is position 3. Note that the subscript starts from 0
and space is counted as 1 character.
name='I love python'
>>> name.find('ove',0,10)
3
The above example searches for a substring ‘ove’ in the string name.0 is the beginning
index from where it has to start searching and 10 is the ending index from where it has
to stop searching. Means it has to search only in string ‘I love pyth’.
14.count() method
count() method is used to count the number of times a particular character or string appears in
a given string.
isdigit() method is used to check if the particular string is digit (number) or not and
returns Boolean value true or false.
>>>name2="123"
>>>name2.isdigit()
True
>>name1="123keyboard"
>>name1.isdigit()
False
>>>name2="123"
>>>name2.isnumeric()
True
>>name1="123keyboard"
>>name1.isnumeric()
False
19.isalnum() method
isalnum() method is used check string is alpha numeric string or not.
>>>name2="123"
>>>name2.isalnum()
True
>>>name1="123computer"
>>>name1.isalnum()
True
>>>name3="Monika"
>>>name3.isalnum()
True
>>> name=”hello@3”
>>>name.isalnum()
False
str() method is used convert non string data into string type.
>>>str(576)
'576'
25.index() method
Index method is used to search for a character or substring. It has 3 arguments. First
specifies the string to be searched. Second specifies the beginning position from where
to start searching and third argument is the end position. This method ( ) is same as
find(), but raises an exception if string not found.
>>> name="Hello world"
>>> name.index("a",3,8)
ValueError: substring not found
>>> name.index("e",1,8)
1
26. count( ) Method
count() function in an inbuilt function in python programming language that returns the number
of occurrences of a substring in the given string.
The count() function has one compulsory and two optional parameters.
Mandatory paramater:
1)substring – string whose count is to be found.
Optional Parameters:
1)start (Optional) – starting index within the string where search starts.
2)end (Optional) – ending index within the string where search ends
>>> a="#pythonisfun#c++isnotfun"
>>> a.count("is")
2
>>> a.count("is",10,20)
1
27. replace()
The replace() method replaces a specified phrase with another specified phrase.
Example
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
Output
three three was a race horse, two two was three too."
Another example
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
three three was a race horse, two two was one too."
The partition() method searches for a specified string, and splits the string into
a tuple containing three elements.
The first element contains the part before the specified string.
Example
Search for the word "bananas", and return a tuple with three elements:
Example
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
('I could eat ', 'bananas', ' all day')
Join all items in a tuple into a string, using a hash character as separator:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
John#Peter#Vicky
2. chr() Method
c=0
name=input("enter a string: ")
for a in name:
if a=='a' or a=='e' or a=='i' or a=='o'or a=='u':
c+=1
print("The count of vowels is",c)
Output
enter a string: hello be here
The count of vowels is 5
3. WAP to input your name and print each character of your name in
same line with a space between.
name=input("enter a string: ")
for a in name:
print(a,end=' ')
Output
enter a string: hello
h e l l o
lc=uc=dc=0
name=input("enter a string: ")
for a in name:
if a.isupper():
uc+=1
elif a.islower():
lc+=1
elif a.isdigit():
dc+=1
print("The count of uppercase letters is",uc)
print("The count of lowercase letters is",lc)
print("The count of digits is",dc)
Output
enter a string: Meditation KILLS StRess 123
The count of uppercase letters is 8
The count of lowercase letters is 13
The count of digits is 3
name=input("enter a string")
print(name.swapcase())
Output
enter a stringPytHOn RocKs
pYThoN rOCkS
Output
enter a string : malayalam
palindrome
Another solution
string=input("enter a string")
newstring=""
for i in range (1, len(string)+1):
newstring=newstring+string[-i]
if newstring==string:
print("pallindrome")
else:
print("not a pallindrome")
a=input("enter a string")
print(a.capitalize())
s=0
a=input("enter a string")
for i in a:
if i.isdigit():
s=s+int(i)
print(s)
9. WAPS to accept a main string and substring and count the number of
times substring appears in main string.
a=input("enter a string")
b=input("enter a substring")
print(a.count(b))
a=input("enter a string")
x=a.find('.')
print(a[x+1:])
12. WAP that enters a phone no with 10 characters and 2 dashes. Check
if phone no is valid. (Phone no format : 017-555-3462)
14. Write a program that reads a line and displays the longest
substring of the given string having just the consonants.
Punct=’(!()-[]{};:'"\,< >./?@#$%^&*_~'
str=input(“Enter the string”)
for x in str:
if x in punct:
str[x]=’ ‘
print(str)
x = "hello world"
print(x[:2], x[-2:])
print(x[2:-3], x[-4:-2])
Ans he ld
llo wo or
2.
str='''PythonSchool
GreaterNagar'''
print("Line1",str[19],end='#')
print("\t",str[4:7])
print(str*3,str[20:],sep="***")
Ans 1. Pytho
2. Pyt
3. Pytho
4. nIsFun
4. Give the output of the following code
a = True
b = False
c = False
if a or (b and c):
print(" PYTHON IS BEST")
else:
print("python is best")
Ans 18
6. From the string S = “CARPE DIEM”. Which ranges return “DIE”
and “CAR”?
Ans
1.S[6:9]
2.S[0:3]
Ans ThaodforEverything
14. Design a program to take a word as an input, and then
encode it into Pig Latin. A Pig Latin is an encrypted
word in English, which is generated by doing the
following alterations:
The first vowel occurring in the input word is placed at
the start of the new word along with the remaining
alphabet of it. The alphabet is present before the first
vowel is shifted; at the end of the new word it is
followed by “ay”.
butler" = "utlerbay"
"happy" = "appyhay"
"duck" = "uckday"
"me" = "emay"
"bagel" = "agelbay"
"history" = "istoryhay
Find the output of the following code:
OldText="EGoveRNance"
n=len(OldText)
NewText=""
for i in range (n):
if ord(OldText[i])>=65 and ord(OldText[i])<=73:
NewText+=OldText[i].lower()
elif OldText[i]=="a" or OldText[i]=="n":
NewText+="*"
elif i%2==0:
NewText+=OldText[0:3]
else:
NewText+=OldText[i].upper()
print("The New Text After Changes: ",NewText)
Answe egEGoVEGoREGo**CEGo
r