Strings
Strings
CLASS XI
INFORMATICS PRACTICES
In Python, Strings are arrays of bytes representing
Unicode characters.
Python even a single character is a string
my_string = 'Hello’
Introduction
to my_string = "Hello”
Mystring=“Computer Science”
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C O M P U T U T S C I E N C E
To access/print a particular character of a string use []
print(stringvariable[index])
Mystr=“Strings in Python”
Accessing print(Mystr[4])
characters in print(Mystr[7])
a String print(Mystr[len(Mystr]-1]
• A=‘Hello’
• print(A*3) #HelloHelloHello
Operations in Strings
in
Membership - Returns True if a substring exists in the given string
print(“in” in “Pin”) True
print(“IN” in “pin”) False
print(“cs” in “c s”)
False
not in
Membership – Returns True if a substring does not exist in a given string
len()
• returns number of characters in a string
max() x
Built in • print(max('Maximum’))
functions min() a
with • print(min('boolean’))
any() True
• print(any('special’))
MOST STRINGS ARE
IMPORTANT IMMUTABLE
PROPERTY OF
STRINGS
AN EXTREMELY IMPORTANT Changes cannot
CONSIDERATION …..
STRING VARIABLE CANNOT be made to
BE CHANGED strings
an immutable object can’t be
changed after it is created.
Example
IMMUTABLE int, float, bool literals
DATA TYPES
Strings
tuples
IMMUTABLE SIMPLE DATA TYPES
print(id(10))
x=10
140457543596032
print(id(x)) 140457543596032
print(id(20)) 140457543596352
140457543596352
x=20
140457543596352
print(id(x))
y=20
print(id(y))
s="BRONZE MEDAL"
w ‘ ‘ True
Traversal means processing each
character
Traversal in
Strings
Traversal in Python is possible in two
ways
Character Index Iteration
Iteration
Character traversal
for i in stringvar: #here i is each character of the string
print(i)
String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
Example question of Character
traversal
Write the number of uppercase and lowercase letters in a String
Programs practice
What do you think is the output?
s='new year'
a=id(s)
print(a,type(a))
Output
140130896553008 <class 'int'>
s='happy new year'
140130896553072
b=id(s)
False
print(b)
print(a==b)
Do you think both print statements
will give the same result?
s='hello'
print(id(s)) Output
s=s+'there' 139957288719472
139957288719728
print(id(s))
What is the output?
>>>example = "snow world"
>>>example[3] = 's'
>>>print(example)
Recap –
Answer the
following
TypeError
Strings are immutable
What is the output?
>>>example = "snow world"
Recap – >>>max(example),min(example),any(example)
Answer the
following
w ‘ ‘ True
Traversal means processing each
character
Traversal in
Strings
Traversal in Python is possible in two
ways
Character Index Iteration
Iteration
Character traversal
for i in stringvar: #here i is each character of the string
print(i)
String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
Example question of Character
traversal
Write the number of uppercase and lowercase letters in a String
Else
for i in range(0,len(string),2):
print(string[i])
Write a program to print all position
numbers where there is a vowel in a string
This question requires index traversal
Take in a string string=input('Enter a string')
for i in range(0,len(string)):
Start iterating through index if(string[i] in 'aeiouAEIOU’):
print('Vowel at',i)
Check if character at that index is a
vowel
If yes print index
Write a program to find if a string is
a Palindrome or not
s=input('enter something')
y=''
for i in s:
y=i+y
if y==s: s=input('enter something')
print('tis a palindrome') for i in range(0,len(s)//2):
else: if s[i]!=s[len(s)-i-1]:
print('not a palindrome ') print('not a pal’)
break
else:
print('tis a pal')
Find the output:
s='Mango'
for i in range(len(s)):
print(s[i]*i)
Output
a
nn
ggg
oooo
Find the output
s='python'
for i in range(0,len(s)):
for j in range(0,i+1):
print(s[j],end=‘’)
print() Output
p
py
pyt
pyth
pytho
python
Find the output
mystr="HARMONIOUS"
L = len(mystr)
str2='' Output
str3='' ahm$nooi$$
for i in range(0,L,2):
str2=str2 + mystr[i+1]+mystr[i]
for ch in str2:
if ch>='R' and ch<='U’:
str3+='$’
else:
str3+=chr(ord(ch)+32)
print(str3)
Chocolate Question
#This question will be done in a different
way later
Read two strings and check if string1 is prefix from the string2.
ForEg-
string1: ever
string2: evergreen
Output: prefix
String1: All
String2: Alchemist
Output: No
Chocolate Question
Algorithm string1=input('Enter the substring')
string2=input('Enter the main string’)
Take substring and string flag=True
Start matching each character of String and Substring for i in range(0,len(string1)):
upto the length of Substring if(string1[i]!=string2[i]):
flag=False
If there is any instance where character does not match break
break if(flag==True):
print('Prefix')
If the loop has been broken then Substring is not a prefix else:
Else substring is a prefix print('No')
Practice Question
Read two strings and check if string1 is prefix or postfix from
the string2.
If you copy from internet or have done advanced do not
use any string method or slicing. Any such response will
not win a chocolate
Negative Indexing in Python
Python also allows negative indexing of characters from Right to left
Mystring=“Computer”
-8 -7 -6 -5 -4 -3 -2 -1
C O M P U T E R
Find the output
Output
s='Strings are fun'
s
for i in range(-9,-1,2):
a
print(s[i])
e
f
For Example
s='Air Conditioner’
print(s[2:9])
Output
r Condi
If the step is mentioned as -1 then default start is len(string)-1 and default stop is 0
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Slicing
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
R o t t e n F r u i t 1 2 3
y=s[1::3]
pe3p Al2
print(y) 2
z=s[6:7]
print(z)
pple 2
a=s[-15:15]
print(a)
Practical Question : Ceaser Cipher
In Cryptography, a Caesar cipher is a very simple encryption techniques in which
each letter in the plain text is replaced by a letter some fixed number of positions
down the alphabet list in a cyclic manner. For example, with a shift of 3, A would be
replaced by D, B would become E, and so on.
The method is named after Julius Caesar, who used it to communicate with his
generals. ROT-13 ("rotate by 13 places").
Methods in
Strings Functions Methods
A function is not bound to Methods are bound to
any object objects
A method is a function
A function can work with Methods work implicitly with
that “belongs to” an
different kinds of arguments the objects they are created
object. for
s='computer science' #1 capitalize will return the string after converting the first
print(s.capitalize()) #1 letter into upper case
print(s) #2 #Output
#2 string will not change because Strings are immutable
Computer science
print(id(s)) #6 computer science #3 Here s variable is being reset to a new string with first
140690212087608
s=s.capitalize() #3 letter capital
Computer science
print(s) #4 140690211755544
#4 Hence the id’s of statement 5 and 6 will be different
print(id(s)) #5
Back
title()
Return a titlecased version of the string: title() capitalize()
words start with uppercase characters Converts first Converts first
letter of every letter of first
all remaining cased characters are lowercase. word word
s='happy new year' Even if first letter Only works if the
print(s.title()) is not a letter, it first letter is a
y='2020ad is a year of sorts'
convert the first capital letter
print(y.title())
letter in the word
Output
Happy New Year
2020Ad Is A Year Of Sorts
Back
upper()
Return a copy of the string converted to uppercase.
#Output
COMPUTER SCIENCE 083PYTHON
Back
lower()
Return a copy of the string converted to lowercase.
s=‘ComPutER SciENCe’
print(s.lower())
#Output
computer science
Back
swapcase()
Return a copy of the string with uppercase characters converted to lowercase and
vice versa.
s=‘ComPutER SciENCe’
print(s.swapcase ())
#Output
cOMpUTer sCIencE
Back
center(width[, fillchar])
Return centered in a string of length width. s='Programming'
print(s.center(10,'*'))
Padding is done using the specified fillchar
#Output
Default is a space Programming
s='stars' s='Happy'
print(s.center(10,'*’)) y=s.center(20)
print(y,'*’)
#Output
**stars*** #Output
Happy *
Back
count()
Return the number of occurrences of substring sub in string S[start:end].
Optional arguments start and end are interpreted as in slice notation.
#Output
2
John,Simon,Aryan
John,simon,aryan
Back
startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False
prefix can also be a tuple of prefixes to look for
With optional start, test string beginning at that position.
With optional end, stop comparing string at that position.
print(x)
find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found
Optional arguments start and end are interpreted as in slice notation.
Return -1 if sub is not found. print("abcdef".find("cd") == "cd" in "abcdef")
print("ccdcddcd".find("c"))
#Output
#Output False
0 print(‘ccdcddcd’.find(‘dcd’)
print("ccdcddcd".find("cd")) print(‘alphabets’,find(‘phe’)
#Output
#Output 2
1 -1
find(sub[,start[,end]]) part 2
Write a code to find the second occurrence of
‘India’ in the sentence ‘India is a South Asian
country. India comes from word Indus’ s=input('Enter the sentence')
sub=input('Enter the substring')
Modify the code such that it prints all the indexes pos=-1
of the word in a sentence. Take the word and for i in range(s.count(sub)):
sentence from the user pos=s.find(sub,pos+1)
print(pos)
Back
rfind(sub [,start [,end]])
Return the highest index in the string where substring sub is found
Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
Output
s='Strings and String Methods are important'
40
print(len(s)) 12
Strings And String
print(s.find('String')+s.rfind('String')) Methods Are
print(s.lower().title()) Important
Back
Class XI
STRINGS – SESSION 6,7,8
format()
The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}.
The format() method returns the formatted string.
Back
Islower() isupper() isalpha() isalnum()
islower()
Check if all the characters in the text are in lower case
isupper()
Check if all the characters in the text are in upper case
isalpha()
Check if all the characters in the text are letters
Isalnum()
Check if all the characters are alphabets or digits
Example
txt ='CompanyX' txt ='COMPANY X'
x=txt.isupper() x=txt.isupper()
y=txt.isalpha() y=txt.isalpha()
z=txt.islower() z=txt.islower()
print(x,y,z) print(x,y,z)
Back
isdigit(), isdecimal(), isspace(), istitle()
isdigit()
Check if all the characters in the text are digits
isdecimal()
check if all the characters in the unicode object are decimals (Meaning decimal number system)
istitle()
Check if each word start with an upper case letter
Isspace()
Checks if the character is a space or not
Example
txt ='125'
x=txt.isdigit() True
y=txt.isdecimal() True
False
z="Hello there".istitle() True
a='Hello 123'.istitle()
print(x,y,z,a)
Back
Let’s Revise:
WAP to count the number of uppercase, lowercase, digits , space and any special
characters in a string.
Eg: Self Test-12@11
Uppercase: 2
Lowercase:6
Spaces: 1
Special character: 2
Digits: 4
ljust() and rjust()
Returns Left or right justified version of strings
txt='Strings'
Strings are important
print(txt.ljust(20),'are important')
Strings************* are immutable
print(txt.ljust(20,'*'),'are immutable') &&&Strings are indexed
Strings can be sliced
print(txt.rjust(10,'&'),'are indexed')
print(txt.rjust(20),'can be sliced')
Back
join()
01 02 03 04
The join() method A string must be string.join(iterable) Needs atleast two
takes all items in specified as the element long
an iterable and separator. iterable
joins them into one
string.
Join() Examples
txt='Python'
txt='P'
print('*'.join(txt))
print('*'.join(txt))
print(txt.join('**'))
P*y*t*h*o*n P
*Python*
Back
oldvalue Required. The string to search for
#Output
three three was a race horse, two two was three too.
one one was a race horse, two two was one too.
Back
Example replace()
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three",2)
print(x)
print(txt)
#Output
three three was a race horse, two two was one too.
one one was a race horse, two two was one too.
Back
strip() lstrip() rstrip()
string.strip(characters)
Returns a trimmed version of the string
Remove spaces at the beginning and at the end of the string
Space is the default character to remove
#Output #Output
To remove blank spaces o remove any characters a
To remove blank spaces check o remove any characters aT
To remove blank spaces To remove any characters a
Back
string.split(separator, maxsplit)
Split() –
Important You can specify the separator, default separator is any whitespace.
method When maxsplit is specified, the list will contain the specified number of
elements plus one.
separator Optional. Specifies the separator to use when splitting the string.
By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1,
which is "all occurrences"
split() Examples
txt='Split method is used extensively in Python' txt='Split method is used extensively in
l=txt.split() Python'
print(l) l=txt.split('l')
print(type(l)) print(l)
['Split', 'method', 'is', 'used', 'extensively', 'in', 'Python'] ['Sp', 'it method is used extensive', 'y in Python']
<class 'list'>
txt=input() #Output
l=txt.split() Paris is the Capital of France
for i in l: Paris
if(i[0].isupper()): Capital
print(i) France
Exercise: To find all 4 letter words
from a sentence
txt=input()
Iran is a country in Asia
l=txt.split() Iran
for i in l: Asia
if(len(i)==4):
print(i)
H.W- Practical List Q12
Back
RECAP
WAP to count the number of words in a
string which start with vowel characters.
splitlines()
Splits the string at line breaks and returns a list
string.splitlines(keeplinebreaks)
Same as split(‘\n’)
Back
Returns a tuple where the string is parted into
three parts
The first element contains the part before the
specified string.
The second element contains the specified
string.
partition()
The third element contains the part after the
string.
This method search for the first occurrence of
the specified string.
string.partition(value)
value Required. The string to search for
('homo sapiens', '', '')
Examples partition()
txt='homo sapiens' txt='homo sapiens' txt='homo sapiens'
print(txt.partition(' ')) print(txt.partition('o')) print(txt.partition('S'))
#Output #Output #Output
('homo', ' ', 'sapiens') ('h', 'o', 'mo sapiens') ('homo sapiens’, ‘ ‘, '')
txt='homo sapiens'
print(txt.partition('h'))
#Output
('', 'h', 'omo sapiens')
Exercise : Find the output
s="a@b@c@d" print('cd'.partition('cd'))
a= s.partition("@") print('abef'.partition('cd'))
print(a)
b=s.split("@",3) #Output
print(b) ('', 'cd', '')
('abef', '', '')
#Output
('a', '@', 'b@c@d')
['a', 'b', 'c', 'd']
Back
rpartition()
Returns a tuple where the string is parted into three parts
The rpartition() method searches for the last occurrence of a specified string, and
splits the string into a tuple containing three element