CLASS :XII
COM /MATH’S /BIO /HUM
SUB: COMPUTE SCI. WITH
PYTHON -CODE-[083]
SESSION:2020-21
1. String Data Type
String literals in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
var1 = 'Hello World!'
var2 = "Python Programming“
print(var1)
print(var2)
An individual char in a string is accessed using a subscript(index).
The subscript should always be an integer(positive/negative) and
begin with 0.
String Operator
Two basic operator of string are :
1] ‘ +’ - String Concatenation operator
The + operator creates a new string by joining the two strings.
+ (String Concatenation Operator)
Example :
str1="Key-"
str2="board"
print(str1 + str2)
OUTPUT :
Key-board
String Operator
2] ‘*’ String replication ( Multiplication) operator
* operator is used with numbers, it performs multiplication
and returns the product of the two numbers.
* [replication operator ]
str1="Key"
print(str1*4)
OUTPUT : KeyKeyKeyKey
print('#' * 3)
OUTPUT :- ###
Membership Operators
There are two membership operators for strings .
1] in :- returns True if a character or a substring exists in the
given in string , false otherwise.
2] not in :- returns true if a character or substring does not exist in
the given string, false otherwise.
Membership Operators
Example :-
str='School' “a” in “Keyboard” => True
“in” in “india” => True
if ("a" in "school"):
print("a is found in string") “jap” not in “japan” = >
else: -> will give False because “jap” is
print("a is not found in string") contained by “japan”
OUTPUT: “ABC” not in “hello”
a is not found in string -> will give True because “ABC” is
not contained by “hello”
Comparison Operator
All the relational operator apply to string. Example :
Common character with their original value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 To 90
‘a’ to ‘z’ 97 To 122
Operator Result
'abc'=='abc' True
'abc'==‘Abc' False -> letter is different
'a‘ !=‘A' True
'a' <'A' False
'abc' <'ABC' False -> abc is higher ASCII value then ABC .
Note :- Python compares two strings through relational operators using char-by-
char comparison of their unicode value ….
Determining original value of char :-
In python ord() , a built-in-function that takes a single
character and returns the corresponding ordinal
unicode value .
Example :-
>>>ord(„A‟)
65
>>>ord(65)
„A‟
>>>ord(97)
„a‟
Accessing characters in strings by index in Python
it’s possible to access individual characters of a
string by using array-like indexing syntax.
Term ‘String slice’ refers to a part of the string,
where strings are sliced using a range of index.
Example :-
String [start : end ]
String [start : end : n]
Accessing characters in strings by index in Python
Word= ‘MICROSOFT’
Positive indexing 0 1 2 3 4 5 6 7 8
M I C R O S O F T
Negative -indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
STRING OUTPUT REASON
Word[ 0 : 9] MICROSOFT Letter starts from 0 index to last index [8]
Word [0 : 3] MIC Letter starts from 0 to 2
Word[2:5] CRO Letter starts from 2 to 4
Word [ -5:-1] OSOF Letters from -5,-4,-3,-2 [excluding -1]
Word[ : 9] MICROSOFT By default index start with 0
Word[ : 4] MICR Letter start from 0 to 3
Word[5: ] SOFT Letter start from 5 to last index…
Word[2 : 8] CROSOF Start from 2 to 7 index ..
Accessing characters in strings by index in Python
Word= „MICROSOFT‟
Positive indexing 0 1 2 3 4 5 6 7 8
M I C R O S O F T
Negative -indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
STRING OUTPUT
>>>Word[ 3:] , Word[:4] ROSOFT MICR
>>>Word[:4] + Word[4:] MICROSOFT
>>>Word[1: 6 : 2] IRS
>>>Word[-9: -3 : 3 ] MR
>>>Word[ : : -2 ] TOOCM
>>>Word[ : : 2 ] MCOOT
>>>Word[ : : -1 ] TFOSORCIM – (reverse string)
>>>Word[2 : 8] CROSOF
Accessing characters in strings by index in Python
Word= ‘SAVE MONEY’
Positive indexing 0 1 2 3 4 5 6 7 8 9
S A V E M O N E Y
Negative -indexing -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
STRING OUTPUT
>>>Word[1:3] ‘AV’
>>>Word[ : 3] SAV
>>>Word[3 : ] E MONEY
>>>Word[ : ] SAVE MONEY
>>>Word[ -2 : ] EY
>>>Word[ : -2 ] SAVE MON
Strings Functions
and methods
String Method :
String manipulation is very useful and widely used in all
the language. Python’s built-in string methods are
available through class string.
1] Method name :- len()
Syntax :- len(str) , len(list)
Example :-
str="Computer Science with Python ##" # Example of string.
list_name= ["CPU", "Keyboard", "Mouse","Hub"] #Example of List
x=len(str)
y=len(list_name)
print("Length of string 1=", x)
print("Length of Data Type List=",y)
2] Method name :- capitalize()
This method returns a copy of the string with its first
character capitalized.
Syntax :- <string.object>.<Methodname>
Example :-
str=“computer science " # Example of string.
print(str.capitalize())
Will print :- Computer science
3] Method name :- find(sub_string)
method name :- find(sub_string, start , end)
This method returns a index position if sub sting is found within
the slice range of string and returns -1 if it is not found.
Example :-
str="string is in lower case" # Example of string.
sub="is"
print("THe position of string at==", str.find(sub))
OUTPUT:
THe position of string at== 7
4] Method name :- isalnum()
Returns true , if all characters in the string are alphanumeric (alphabets or
numbers) or at least any one of them , otherwise returns False.
Example:-
str="Computer2019" # Example of string.
if str.isalnum():
print("The string contains Alpha- Numeric!!")
else:
print("String is not contain Alpha-Numerics!!.")
OUTPUT :-
The string contains Alpha- Numeric!!")
5] Method name :- isalpha()
Returns True if all characters in the string are alphabetic and
there is at least one character, False otherwise.
Example:-
str="Computer" # Example of string.
if str.isalpha():
print("The string contains only Alphabets!!")
else:
print("All chararcters are not alphbetic in String !.")
OUTPUT :-
The string contains only Alphabetic!!
6] Method name :- isdigit()
Returns true , if all characters in the string are digits or numbers , otherwise
returns False.
Example:-
str="2019" # Example of string.
if str.isdigit():
print("The string contains Number!!")
else:
print("String is contain alphanumeric char.!!.")
OUTPUT :-
The string contains Number!!"
7] Method name :- count( )
Returns the no. of occurrence of substring I the str4ing which begins at
position start and ends at position end.
Example:-
str="Computer Science with python " # Example of string.
c= str.count('with')
print("The word 'with' presents=", c , “ =No.of Times")
OUTPUT :-
The word 'with' presents= 1 =No.of Times
8] Method name :- islower()
Returns True if all characters in the string are are lowercase or in
small case, False otherwise.
Example :-
str="Computer" # Example of string.
if str.islower():
print(“This is string is in Lower Case Format!")
else:
print("All char in string is not in Lower case!.")
OUTPUT :-
All char in string is not in Lower case!.
9] Method name :- isupper()
Returns True if all characters in the string are in Upper Case , otherwise
returns False.
Example :-
str=“KEYBOARD" # Example of string.
if str.isupper():
print("All chars of string is in Upper Case")
else:
print("All chars of string is not in Upper case!.")
OUTPUT :-
All chars of string is in Upper case!.
10] Method name :- lower()
Returns copy of string converted to Lower Case.
Example:
str1="Computer Science with python " #Example of string.
c= str1.upper()
print("Sting in Lower/Small Case=", c)
OUTPUT:
Sting in Upper Case= computer science with python
11] Method name :- upper()
Returns copy of string converted to Upper Case.
Example:
str1="Computer Science with python " #Example of string.
c= str1.upper()
print("Sting in Upper Case=", c)
OUTPUT:
Sting in Upper Case= COMPUTER SCIENCE WITH PYTHON
12] Method name :- isspace()
This method returns true if there are only whitespace characters
in the string and there is at least one character, false otherwise.
.Example:
str = “ ";
print str.isspace()
str = "This is string example....wow!!!";
print str.isspace()
OUTPUT:
True
False
13] Method name :- split ( )
The split() method breaks up a string at the specified separator
and returns a list of substring.
Example:1
str1=input("enter the Line string:-")
print(str1.split())
OUTPUT:
enter the Line string:- there are two type of mode in python
['there', 'are', 'two', 'type', 'of', 'mode', 'in', 'python']
14] Method name :- istitle ( )
The istitle() method returns True if string is properly in “Title
case” else return false..
Example:
str1="All Learn Python"
print(str1.istitle()) #output – True
str1="All learn python"
print(str1.istitle()) #output- False
str1="ALL LEARN PYTHON"
print(str1.istitle()) #output – False
15] Method name :- join(sequence)
Returns a string in which the string elements have
been joined by a string seperator.
# .join() with lists
numList = ['1', '2', '3', '4'] OUTPUT:
separator = ', ' 1, 2, 3, 4
print(separator.join(numList)) 1, 2, 3, 4
# .join() with tuples s1.join(s2): 1abc2abc3
numTuple = ('1', '2', '3', '4') s2.join(s1): a123b123c
print(separator.join(numTuple)) >>>
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3„
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2
# 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))
16] Method name :- swapcase()
The string swapcase() method converts all uppercase characters
to lowercase and all lowercase characters to uppercase
characters of the given string, and returns it.
The format of swapcase() method is:
string.swapcase()
# example string
string = "THIS SHOULD ALL BE LOWERCASE."
print(string.swapcase())
string = "this should all be uppercase."
print(string.swapcase())
string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase())
OUTPUT:
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.
17] Python String partition()
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.
->The second element contains the specified string.
->The third element contains the part after the string.
Example: How partition() works?
output :
18] Python String lstrip()
Python String lstrip() method returns a copy of the string with
leading characters removed (based on the string argument passed).
If no argument is passed, it removes leading spaces.
Example : How it works?
Output:
Python is programming Language
Python is programming Language
19] Python String rstrip()
The rstrip() method returns a copy of the string by removing the
trailing characters specified as argument. If the characters
argument is not provided, all trailing whitespaces are removed from
the string.
Trailing characters are those characters which occur at the end of
the string (rightmost part of the string).
Example : How it works ?
OUTPUT
Ord() - function returns the ASCII code of the character .
Example:
ch='b'
print(ord(ch)) OUTPUT:
ch='z' 98
print(ord(ch)) 122
Chr()- function returns character represented by the inputted ASCII
character .
Example:
ch=97
print(chr(ch)) OUTPUT:
ch=66 a
print(chr(ch)) B
To count the no. of space in given string.
ANS: python code :
str1=input("enter the string:-")
cn=0
for i in str1:
if i.isspace():
cn+=1
print('total no. of space=',cn)
OUTPUT :-
enter the string:- my school name is sam
total no. of space= 4
Program to read lines and print no. of s
mall/Capital/alphbets/digits ..
str=input("enter the string.") OUTPUT:
lc=uc=di=al=0
enter the string. hello 123 my name
for a in str: Number of Upper Case Letters= 0
if a.islower(): Number of Lower Case Letters= 11
lc+=1 Number of digits= 3
Number of alphabets= 11
elif a.isupper():
uc+=1
elif a.isdigit():
di+=1
if(a.isalpha()):
al+=1
print("Number of Upper Case Letters=",uc)
print("Number of Lower Case Letters=",lc)
print("Number of digits=",di)
print("Number of alphabets=",al)
PRACTICE CODE BASED ON STRING DATA TYPE :
Code :1 Code :4
Code :2
Code :3