strings
strings
XI
Definition
A Python string is a sequence of characters stored in contiguous memory
locations.It is an immutable data type.
String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single, double or triple quote.
Each character can be individually accessed using its index. These characters can be
accessed using either forward indexing or backward indexing.
You can access any character as <stringname>[index].
The index can be a forward index or a backward index.
➢ 0, 1, 2,.... In the forward direction
➢ -1, -2, -3….. In the backward direction
2
XI
Indexing
Forward Indexing
0 1 2 3 4 5
string P Y T H O N
-6 -5 -4 -3 -2 -1
Backward Indexing
3
XI
Traversing a string
Individual character of a string can be accessed using the method of indexing. Each
character of a string is referred by an integer which is known as Index or subscript.
The index or subscript starts from 0 and must be an integer.
Traversing a string means accessing all the elements of the string one after
another by using the subscript or index where the index or subscript is given
within [ ] with the stringname.
The index used to access character of a string can be positive or negative integers.
0 1 2 3 4 5 6 7
String (str) C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1
Output
Amar Shah Lived in the King's Palace at Hyderabad
His best book was entitled as The Dream of "Doll" uncovered
6
XI
Assigning a string
String can also be created using Escape sequence characters as a part of the string.
The following example shows the use of \n and \t escape sequence characters for tab
and new line
message = "Programming Language:\t Python\n Developed
by Guido Van Rossum"
print(message)
Output
Programming Language: Python
Developed by Guido Van Rossum
7
XI
Assigning a string
Python does not support a character data type, these are treated as strings of length
one.
A string without any character inside is known as Empty String. When an Empty string
is displayed using print(), a blank space gets displayed.
>>ch=""
>>print(ch)
''
8
XI
Operations on Strings
OPERATIONS
String
Concatenation Replication Comparison Membership
Slicing
9
XI
Concatenation
The + operator takes two strings as operands and results a new string by joining the
two operand strings.
Syntax : string literal 1/object 1+string literal 2/object 2
Example :
>>a="Computer"
>>b='Science'
>>print(a+b)
Output
ComputerScience
10
XI
Replication
The * operator as a replication operator needs two operand i.e a string and an
integer. Python replicates the string operand the given number of times.
Output
ComputerComputerComputer
11
XI
Comparison
All relational and comparison operators (==, >, <, <=, >=, !=) can be used to
compare two strings .
The comparison will be done on the basis of ASCII value of the character. Python
compares first element of each string. If they are the same ,it goes on to the next
element and so on .
12
XI
Common Characters and Ordinal Values
CHARACTERS ORDINAL VALUES
0 to 9 48 to 57
“A” to “Z” 65 to 90
“a” to “z” 97 to 122
Python provides a built in function ord() that takes in a single character and
returns the ordinal value.
Syntax : ord(<single-character>) ch=’a’
ord(ch)
>>ord("a")
97
13
XI
Membership
The operators in and not in are used to check whether a string exists in the given
string or not. The operands of in and not in operators are strings.
14
XI
String Slicing
String slicing refers to the part of the string or a subset of a string.This subset of a
string (the substring) is termed as slice. To extract the slice two indexes are given
in square bracket separated by a colon (:).
Example : string1[2:5]
C o m p u t e r
0 1 2 3 4 5 6 7
15
XI
String Slicing
However , while slicing string, start, end and step can be omitted.
16
XI
String Slicing
The start and end values can be –ve integers in which Python counts from
the right hand side.
Example :
Example: h e l l o
0 1 2 3 4
s=”hello” -5 -4 -3 -2 -1
print(s[5]) -> will cause error as 5 is invalid
index-out-of-bound
But, print(s[4:8]) -> valid
print(s[5:10]) -> valid
18
XI
String Slicing
0 1 2 3 4 5 6 7
String (str) C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1
Output
print(str[3:7] ) pute
print(str[4:] ) uter
print(str[:6] ) Comput
print(str[1::2] ) optr
print(str[-3:]) ter
19
XI
Answer the following :
String (str) C o m p u t e r S c i e n c e
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
20
XI
Solution:
21
XI
Find the output :
A = "Passionate Programmer"
22
XI
Solution :
A = "Passionate Programmer"
23
XI
String Functions & Methods
len()
capitalize()
lower()
upper()
isupper()
islower()
isdigit()
24
XI
String Functions & Methods
isspace()
isalpha()
lstrip()
partition()
replace()
split()
25
XI
String Functions and Methods
1. len()
Returns the length of the string or the number of characters in the string
Syntax : len(stringname)
Example
>>> str="i love india"
>>> print(len(str))
12
26
XI
String Functions and Methods
2. capitalize()
Returns the copy of the string with the first character capitalised.
Syntax : stringname.capitalize()
Example
>>> str="hello"
>>>print(str.capitalize())
Hello
27
XI
String Functions and Methods
3. title()
Returns a string which has first letter in each word is uppercase and all
remaining letters are lowercase.
Syntax : stringname.title()
Example
>>> str="hello how are you"
>>>print(str.title())
Hello How Are You
28
XI
String Functions and Methods
4. upper()
Returns an exact copy of the string with all the letters in uppercase
Syntax : stringname.upper()
Example
>>> str="learn python"
>>>print(str.upper())
LEARN PYTHON
29
XI
String Functions and Methods
5. lower()
Returns an exact copy of the string with all the letters in lowercase
Syntax : stringname.lower()
Example
>>> str="PYTHON"
>>>print(str.lower())
python
30
XI
String Functions and Methods
6. isupper()
Returns True if all the characters in the string are uppercase letters.
Syntax : stringname.isupper()
Example
>>>word='ABC'
>>>print(word.isupper())
True
31
XI
String Functions and Methods
7. islower()
Returns True if all the characters in the string are lowercase letters.
Syntax : stringname.islower()
Example
>>>word='xyz'
>>>print(word.islower())
True
32
XI
String Functions and Methods
8. isdigit()
Syntax : stringname.isdigit()
Example
>>>word='123'
>>>print(word.isdigit())
True
33
XI
String Functions and Methods
9. isalpha()
Syntax : stringname.isalpha()
Example
>>>word='alpha123'
>>>print(word.isalpha())
False
>>>word='abcdef'
>>>print(word.isalpha())
True
34
XI
String Functions and Methods
10. isalnum()
Returns True if all the characters in the string are alphabets or digits.
Syntax : stringname.isalnum()
Example
>>>word='alpha123'
>>>print(word.isalnum())
True
>>>word='abc123'
>>>print(word.isalnum())
True
35
XI
String Functions and Methods
11. isspace()
Returns True if all the characters in the string are white space.
Syntax : stringname.isspace()
Example >>>word='alpha123'
>>>print(word.isspace())
False
>>>word=' '
>>>print(word.isspace())
True
36
XI
String Functions and Methods
12. split()
Returns a list of strings after breaking the given string by the specified
separator.
Syntax : stringname.split([separator,maxsplit])
Example
>>>word='DPS Mathura Road Delhi'
>>>print(word.split())
['DPS', 'Mathura', 'Road', 'Delhi']
37
XI
String Functions and Methods
>>>word='DPS,Mathura,Road,Delhi'
Example >>>print(word.split(',',0))
['DPS,Mathura,Road,Delhi']
>>>word='DPS,Mathura,Road,Delhi'
Example
>>>print(word.split(',',2)) Max splits
38
XI
Split function
T = "LEARN PYTHON"
#Splits at space
39
XI
String Functions and Methods
13. strip()
Returns a copy of string after removing leading or trailing characters passed as
argument. If no argument is provided, whitespaces are taken by default.
Syntax : stringname.strip(character)
Syntax : stringname.lstrip(character)
41
XI
String Functions and Methods
15. rstrip()
Returns a copy of string after removing trailing characters passed as argument. If no
argument is provided, whitespaces are taken by default.
Syntax : stringname.rstrip(character)
42
XI
String Functions and Methods
16. partition()
Returns a tuple of strings after splitting the string at first occurrence of
Argument. Returns a tuple of length 3.
Syntax : stringname.partition(character)
43
XI
String Functions and Methods
17. find()
Returns the lowest index in the string where the substring is found or within the slice range (if
specified. If not specified, the range is taken as start - 0th index and end - last index. Returns
-1 if sub is not found.
Returns the number of occurrences of a substring in the given string. Returns 0 if not found.
45
XI
String Functions and Methods
19. replace()
Returns copy of string which has replaced all old substring with new substring.
We Learn PYTHON
46
XI
Question 1
Program to traverse a string inputted by user and display it.
47
XI
Question 2
Program to input a string and display the string in reverse order.
Output :
Enter the string : PYTHON
N
O
H
str1=input("Enter the string :") T
str2=str1[::-1] Y
print(str2) P
48
XI
Question 3
Program to input a string and then print the number of uppercase letters, lowercase
letters, alphabets and digits.
Output :
Enter string:EAT 123 code
No of alphabets : 6
No of digits : 3
No of uppercase characters: 3
No of lowercase characters : 4
48
XI
Question 3
Program to input a string and then print the number of uppercase letters, lowercase
letters, alphabets and digits.
str= input("Enter string : ") Output :
cntalpha=0
cntdigit=0
cntupper=0 Enter string:EAT 123 code
cntlower=0 No of alphabets : 6
for ch in str:
if ch.islower() : No of digits : 3
cntlower+=1 No of uppercase characters: 3
elif ch.isupper() :
cntupper+=1
No of lowercase characters : 4
elif ch.isdigit() :
cntdigit+=1
if ch.isalpha() :
cntalpha+=1
print("No of alphabets : ",cntalpha)
print("No of digits : " ,cntdigit)
print("No of uppercase characters : ",cntupper)
print("No of lowercase characters : ",cntlower) 48
XI
Question 4
Write a program that reads a string and creates a new string by capitalising
every alternate letter in the string.
Output :
Enter string:apple
ApPlE
51
XI
Question 4
Write a program that reads a string and creates a new string by capitalising
every alternate letter in the string.
str = input("enter a string ") Output :
length = len(str)
newstr='' Enter string:apple
for i in range(0,length): ApPlE
if i%2==0:
newstr=newstr+str[i].upper()
else:
newstr+=str[i]
print(newstr)
52
XI
Programs
1. Write a program to input a string and a character and count the number of times a
character appears in the string.
2. Write a program to input n number of strings. Accept n from user. Count the number
of strings which have more than 5 characters in it (Do not use any string function)
3. Write a program to accept a string. Create a new string with all the consonants
deleted from the string.
4. Write a Python program to remove the nth index character from a nonempty string. If
input string is “python” and index is 3, Expected output :”pyton”
5. Write a menu driven program to accept a string and do the following operation as per
the choice of the user
a. Display length of string
b. Display no. of words
c. Display no. of vowels
d. Reverse string 64
XI
Question 5
Program to input a string and then check if it a palindrome or not.
54
XI
Question 6
Program that reads a string with multiple words and creates a new string which
capitalises the first character of each word.
str = input("Enter the string ") Output :
length = len(str)
newstr = '' Enter string: i learn python
newstr +=str[0].upper() New string is : I Learn Python
i=1
while i < length:
if str[i] == ' ' and str[i+1] != ' ':
newstr+=str[i]
newstr+=str[i+1].upper()
i+=2
else:
newstr+=str[i]
i+=1
print("New string is ", newstr)
51
XI
Question 7
Program to accept a string and count and display the number of words which are
starting with a vowel
str=input("Enter a string:") Output :
l=len(str)
p=0 Enter a string : i eat
ctr=0 food
while p<=l-1: No of words starting with
if p==0: vowel - 2
if str[p] in "aeiouAEIOU" :
ctr+=1
elif str[p] == " " and str[p+1] != " ":
if str[p+1] in "aeiouAEIOU" :
ctr+=1
p+=1
print("No. of words starting with vowel - ",ctr)
56
XI
Question 7
Program to accept a string and count and display the number of words which are
starting with a vowel
57
XI
Question 8
Program that reads a string and a substring, and then display the number of
occurrences of that given substring in the string.
string=input("Enter a string - ") Output :
sub=input("Enter a substring - ")
lenstr=len(string)
lensub=len(sub) Enter a string: i learn learn
start=ctr=0 python
end=lenstr
while True:
pos = string.find(sub,start,end) Enter a substring: learn
if pos != -1: No of occurrences of learn=2
ctr+=1
start=pos+lensub
else:
break
if start>=lenstr:
break
print("No of occurences of ",sub, "=", ctr)
58
XI
Question 9
Write the equivalent code of islower() for a string. Accept a string. It should print
True if the string has only lowercase letter.
print(valid)
59
XI
Question 10
Write the equivalent code of upper() for a string. Accept a string. It should convert
all lowercase letters to uppercase.
60
XI
Question 11
Write a program to enter a string and form an integer by extracting all digits
from the string in the order they occurred.
61
XI
Question 12
Write a program to accept an identifier and check for its validity. An identifier is valid if it
is starting with a letter or underscore (_) followed by underscore (_ ) and any
alphanumeric character.
import keyword Output :
str=input("Enter a Identifier: ")
valid = True; valid=str[0].isalpha() or str[0]=='_'
if keyword.iskeyword(str):
Enter a Identifier : _ROLLNO
valid = False Valid
length = len(str);
if valid==True:
for i in range(1,length):
if not str[i].isalnum() and str[i]!="_":
valid=False
print(str, " cannot be an identifier ")
break
else:
print(str, " is a Valid identifier")
else:
print(str, " cannot be an identifier ")
58
XI
Question 13
Write a program that accepts a string. Encrypt the string on the basis of given
criteria and print the encrypted string:
● Every letter and digit should be replaced by the next character.
● 9 should be replaced by 0 and
● Z/z should be replaced by A/a.
● All spaces should be changed to *.
● All other special characters should remain unchanged
59
XI
Solution
str=input("Enter a string-")
newstr=""
newch=""
for ch in str:
if ch.isalnum():
if ch=="z":
newch="a"
elif ch =="9":
newch="0"
else:
n=ord(ch)+1
newch=chr(n)
elif ch.isspace():
newch="*"
else :
newch=ch
newstr+=newch
print("Original string -",str)
print("Changed String –" ,newstr)
60
XI
Question 14
Write a program to input the full name (First name, Middle name (optional), and Last
name) of a person, and then display the name in abbreviated form.
For example:
(i) If the name is “Saif Ali Khan”, the output should be “S. A. Khan”
(ii) If the name is “Priyanka Chopra”, the output should be P. Chopra
66
XI
Another solution:
67
XI
Programs
1. Write a program to input a string and a character and count the number of times a
character appears in the string.
2. Write a program to input n number of strings. Accept n from user. Count the number
of strings which have more than 5 characters in it (Do not use any string function)
3. Write a program to accept a string. Create a new string with all the consonants
deleted from the string.
4. Write a Python program to remove the nth index character from a nonempty string. If
input string is “python” and index is 3, Expected output :”pyton”
5. Write a menu driven program to accept a string and do the following operation as per
the choice of the user
a. Display length of string
b. Display no. of words
c. Display no. of vowels
d. Reverse string 64
XI
Find the output :
A = "Passionate Programmer"
69
XI
Solution :
A = "Passionate Programmer"
70
XI
Find the output :
s="ComPutEr"
for i in s:
if i in 'aeiou':
print('*',end='')
elif i.isupper():
print(i,end='')
else: print('-')
71
XI
Solution:
s="ComPutEr"
for i in s:
if i in 'aeiou':
print('*',end='')
elif i.isupper():
C*-
print(i,end='') P*-
else: print('-') E-
72
XI
Find the output :
Name = "ComPUteR"
for x in range(0,len(Name)):
if Name[x].islower():
print(Name[x].capitalize(), end='')
elif Name[x].isupper():
if x%2==0:
print (chr(ord(Name[x])+32),end='*')
else:
print(Name[x-1])
73
XI
Solution:
Name = "ComPUteR"
for x in range(0,len(Name)):
if Name[x].islower():
print(Name[x].capitalize(), end='')
elif Name[x].isupper():
if x%2==0:
print (chr(ord(Name[x])+32),end='*') c*OMm
else: u*TEe
print(Name[x-1])
74
XI
Find the output :
Text1="AIsScE 2019"
Text2=""
i=0
while i < len(Text1):
if Text1[i] >="0" and Text1[i] <"9":
val=int(Text1[i])
val=val+1
Text2=Text2+str(val)
elif Text1[i] >="A" and Text1[i] <="Z":
Text2=Text2+(Text1[i+1])
else:
Text2=Text2+"*"
i+=1
print(Text2)
75
XI
Solution :
Text1="AIsScE 2019"
Text2=""
i=0
while i < len(Text1): I
if Text1[i] >="0" and Text1[i] <"9": Is
val=int(Text1[i]) Is*
val=val+1 Is*c
Text2=Text2+str(val) Is*c*
Is*c*
elif Text1[i] >="A" and Text1[i] <="Z":
Is*c* *
Text2=Text2+(Text1[i+1]) Is*c* *3
else: Is*c* *31
Text2=Text2+"*" Is*c* *312
i+=1 Is*c* *312*
print(Text2)
76
XI
Find the output
1. word = 'DPS:Mathura:Road'
print(word.split(':')) # Splitting at ':'
2. word = 'CatBatSatFatOr'
for i in range(0, len(word), 3): # Splitting at 3
print(word[i:i+3])
3. txt = "apple#banana#cherry#orange"
x = txt.split("#", 1) # Splitting at ‘#’
print(x)
77
XI
Solution:
['DPS','Mathura','Road']
1. word = 'DPS:Mathura:Road'
print(word.split(':')) # Splitting at ':'
Cat
Bat
2. word = 'CatBatSatFatOr'
Sat
for i in range(0, len(word), 3): # Splitting at 3
Fat
print(word[i:i+3])
Or
3. txt = "apple#banana#cherry#orange"
x = txt.split("#", 1) # Splitting at ‘#’
['apple','banana#cherry#orange']
print(x)
78
XI
© CS-DEPT DPS MATHURA ROAD
Happy Learning!!!
Thank you
79
XI