strings in Python
7.1 INTRODUCTION
after going through Conditional Constructs in the previous chapter, we will now discuss Strings
—an important sequence/collection provided by Python.
Think about beads or anything you might string together. You place one bead ata time on to the
cring, Eventually, you end up with some type of ornamentation—perhaps a necklace or a tree
land, But the point is that these items are made up of individual beads.
The same concept used for a necklace made up of beads holds true for strings in computer. When
you see a sentence, you understand that it is made up of individual characters that are strung
Fig. 7.1: String in Real World
The language creates a structure that holds
‘gether by the programming language you use.
and not the computer, knows that so many
“dividual characters together. So, the language,
alphabets or numbers in a row (each number being represented as a character) make a string
° 4 sentence. in Python too, like in real life, we deal with strings.
Noy ‘i
the question arises—
Where have we seen strings before?
¥ecal the simple programs that we have discussed in the previous chapters,yp
rs Ht M/NOF NAN. Cog |
iy
A program to display a Hello message” to the arser Hhat combine
the Python code for this:
aroun
= |
20 2018, 1 |
etd on wind
nsec for
Spout (h
iter on ai
TRESTARTH ci/Users/proet/Appbata/Toca/ Progra
aPrython eython de 32/p400 AULD
In the above example, the sentence we have typed in print() method, Le “Enter your name,
a string, Even though you see a sentence, Python sees a specitic number of characters, Shnilay,
the output message displayed as “HelloRinku” is again a string. So, we CAN say A SLETR More op
less behaves like a variable holding characters or alphabets inside double quotes
7.2 WHAT ARE STRINGS
In Python, a consecutive sequence of characters, which are enclosed or surrounded by singe
("') or double (“") quotes, is known as a string, This sequence of UNICOD!
include a letter, a number, special character, whitespace or a backslash,
eh
eters may
Astring may be specified by pl the member char:
of the sequence within quotes (single, double or triple). Python String, ’
Python treats single quotes the same as double quotes. f
In the above example, we have a string with the names of fruits and space in betweet
viz. Mango#Apple#Grapes (where # indicates a space) enclosed inside single quotes this
representing a string value assigned to the variable ‘Fruits’ Like other integer variables, stilts
are also declared in the same manner using assignment('=") operator,
Triple quotes are typically used for strings that span py_steing = "Python Strings”
multiple lines.
For example,
Fruits = ‘Nango apple Grapes
7.3 CREATING STRINGS |
Strings are among the most popular data types in Python, We can create them by sit!
enclosing characters in quotes (single, double or triple). Python treats single quotes the
as double quotes. Sometimes, triple quotes can be used in Python but they are general)
to represent multiline strings and doc strings. An empty string is that has 0 characte
Creating strings is as simple as assigning a value to a variable 8
For example,
strl = "Hello World
str2 = "Python Programming
Es
B
Fy
cs
5
Fy
2
FA
5
3
2
E
A
re[Bi Python 3.90 Shett
fle_Edt Shell Debug Options Window Help
thon 3.9.0 (tags/v3.9.0:9cf
Ey seo7l Givi UaD64) | on sneer Oct $2020, 15:34:40) (HSC
Type "help", “copyright", “credits*
formation.
>>> strl=
>>> str]
‘Hello World’
or "license()" for more in
Hello World”
| >>> str2s'Python Programming’) ~ !Toxt can be enclosed wit
>>> str2 or double quotes; both are tre
| ‘python Programning’ i |as stings
) >>>
Ln9 Col:
Fig. 7.2: Creating a String
{CIM Text can be enclosed within single or double quotes; both represent a string,
Iso.
python does not support a character type; these are treated as strings of length one, thu:
considered a substring.
For example, ‘2’, ‘b’, ‘c’ are all strings of length one.
swe know, double quotes and single quotes are used to represent string in Python language
and both are interchangeable. But when a string contains special characters such as quotes, we
need to escape them (i.e., with a backslash “\’ character in front of them to indicate the special
nature of the character). The different ways to include quotes inside a string are:
(i) Escape the single quote by placing a backslash before it or use double quotes instead
of single quotes as the enclosing quotes.
>>> as “This is Neera\'s pen.”
>>> print (a)
‘This is Meera's pen. 7
>>> batirite an article on 'AI' briefly."
>>> print (b)
Write an article on 'AI' briefly.
(ii) Ifthe string contains double quotes, we can use single quotes to represent the string
and vice versa so that we don’t have to escape the quotes.
>>> extiirite an article on "AI" briefly."
>>> print(e) ;
Write an article on "AI" briefly.
(li) If there are both single and double quotes in the string, we need to escape the quotes
otherwise it results in a syntactical error.
fal call you.""
>>> de'she said, "I\'11 call you."*
>>> print id)
She said,*r*11 call you."
>>>
| SM: An escape Tequence characters represented as a string with one byte of memory,
5
5
Et
=
ts
=
ma
2
3
Cy
ed z> Empty String
ers inside, having length zero.
An empty string is.a string without any char’
>>> print (str)
>>> ates |
>>> print (str)
As is evident from the above example, string str does not hold any value, i.e. it is an empy
string, Therefore, when we print an empty string, a blank space gets displayed in the next ing
If the statement is very long, then it can be shifted to multiple lines with the line continuatioy
character ('\’), But it shows the result in the same line.
For example,
left Shel_Oebup Options Window Hep
Python 3.6.5 (v3.6.5:£59¢0930b4, Mar 28 2018, ~
16:07:46) [usc v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or “license()" for
more, information.
split in two lines
de> pesst(ad
Here 19 a 2ine opli in evo Lines
If you wish to display the output on the next line, then the use of escape sequence ‘\
becomes mandatory.
For example,
“let ‘Debug Options Window Hep
python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, ~~
16:07:46) (MSC v.1900 32 bit (Intel)} on wind?
Type "copyright", "credits" or “license()" for
more information.
>> cxtve are Indians \n and ve love cur country"
>>> print (c)
ve are Indians
and ve love our country
E4
i
A
ej
Ey
=
3
5
A
2
a
3
a
=
3
EA
5
éwe can also use escape sequence (\t) to provide horizontal space in the output.
for example,
+6.5:£59¢0932b4, Mar 28 2010,
c
35707546) (Msc v.1900 32 bit (Intel)} on wind
Type "copyright", "credits" or “license()" fo
x more information,
o> ale"Kane\t class \t secticat
>>> ad="RIYA\ XT \t bt
>> print (al)
Wass class section
>> pritt (a)
HR OM
> Multiline Strings
Multiline strings are represented using triple single(") or triple double (“"""""”) quotes.
Python 3. 09324, Mar 26 2018, 1
© v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or “license()" for more informa
tion.
boo sett 'Tni
multiline
example"
>>> print (s)
This is a
multiline string
‘students
ve study computer science
Programing language is python
ing isa sequence of characters. We can create them simply by enclosing characters in quotes
oak
| CTMEA stein
Sale, double or triple).
i ACCESSING CHARACTERS (INDEXING) IN A STRING
isp." A€cess individual characters of the string by using the subscript or index value, which
"own as indexing.
~
>> varl = "Hello Horld*
>>> print (varl (0])
z
>>> print (varl (4])
°
>>> print (varl[-8])
1
>>> print (varl [-6])
>>> print (varl[-5])
a
>>>
We can't use float or other types for index as this will result in TypeError. Trying to access#
character out of index range will raise an IndexError.
We can start index value either from the left or from the right. Left or positive index starts from0
and ends with I-Lwhere | is the length of the string and right or negative index starts from-1
to length of the string.
For example,
varl ='Hello World!"
Positive Index Olt? 13 ]4 {5s ey,r eyes)
var HeEev ty lfo wliolt rfaf!
Negative Index 22-1] 0] 9 | 8 [ys asta
Here, each element or character of the string is associated w
by its index value. To access any subscript of a string, we us
the index.
i A
ith an index and can be access
e the square brackets along"15 TRAVERSING A STRING
pesversinga string means accessing each cha
“ racter one after the other by iterating through the
gements of a string using either for or while
loop.
iterating through string using for loop
zach character of the string can be accessed sequentially using for loop. This is done using
ihe indexes, and iterating over it results in displaying the elements of a string, one character
atime.
@
‘computer science!
n str
print (i)
HOTeCaOO
Inthe above code, the loop starts from the first character
of the string ‘str’ and automatically ends when the last
haracter is accessed.
yooserno
(0) Iterating through string using while loop
Like for, while loop can also be used for string traversal. Each element of the string is accessed
one by one and while loop iterates till the end of the inputted string, which can be determined
using standard library function, len() function.
a
RESTART:
#String traversal using while loop gest-py
str = "python Programing!" 7
index = 0 y
flen() function to get length of string fe
while index ‘Hello "eWorld?
Nello World"
>>>
>>> print (¢)
Good Morning
* Morning”
[Python 3.6.5 (v3.6.
900 32 bit (intel)] on win32
Type “copyright”, "credits" or "License()" for more information|
>>> 2 #tbook!
Traceback (most recent call last):
File "cpyshell¢1é>", line 1, in
2 +"book"
TypeError: unsupported operand type(s) for +
746)
‘int* and ‘str!
TypeError will be
CIM: You cannot add ‘str’ and ‘int’ objects. To use ‘+’ operator, data types should be the same.
For example,
6+3=9 — #addition
‘6’ + ‘3 = 63" #concatenation
But the expression—
‘6'+3 shall generate an error as shown in the above output window,
1.6.2 Replicating Strings
The * operator creates a new string by repeating multiple copies of the same string,
File Edt Shell Debug Options Window Help
>>> 3*'Hello *
‘Hello Hello Hello
>>> 2812"
129"
However, you can use concatenation operator ‘+’ with numbers and strings separately for
performing addition and concatenation operation respectively.
Using replication operator *, Python creates a new string that is a number of repetitions of the
put string,Practical Implementation-1 : al
rin an input
Write a program to count the number of occurrences of a characte! Putted string
(Implementing String Traversal) -
function to count the number of times a character occurs in a
fstring
str = input("enter a string: ") Lo.
ch = input ("enter the character to be searched: “)
count = 0
for character in str:
if character == ch:
‘count += 1
Print ("Nunber of times character"/ch, "occurs in the string \
is:", count)
a
RESTART: C:/Users/preeti /appData/Local/Programs/Python
py
Enter a string: Python is easy and Interactive
Enter the character to be searched: e .
Number of times cter e occurs in the string is: 3
Practical Implementation-2
Write a program to input a string from the user and print it in the reverse order withox:
creating a new string.
[fProgram to display string in reverse order
str = input ("enter a string: ")
for i in range(-1,~-len(str)-1,-1)+
print (str(iJ,end='")
a
RESTART: C:/Users/preeti/AppData
str py
Enter a string: Reversing string
gnirts gnisrever
7.6 SPECIAL STRING OPERATIONS
String can be manipulated using operators like concatenate (+), repel
operator like in and not in.
ion (*) and membersti
‘OPERATIONS Str1 > str2
Stringirange)
Fig. 7.4: Common String Operations
7.6.1 Concatenating Strings
7
Concatenation refers to creating a new string by adding two strings. The + operator j2i"*”
concatenates strings written on both sides of the operator and creates a new string.
|
(CTM: To concatenate means to join. “A
Es
e
=
fs
=
z
3
2
2
rs
3S
2
£
5
3
ulCUTIES CuPCMT ls Lule.
For example,
>>> str= "python"
>>> str * 3 fusing variable str
‘pythonPythonPython!
bos ty) Lise
Traceback (most recent call last)? .
File “", line 1, in
tee
TypeError: can't multiply sequence by
non-int of type ‘str!
CTM: The * operator has to either have both operands of the number types (for performing
multiplication) or one string type and one number type (for replication). It cannot work with boty
Operands of string types.
The last statement shall result in an error because strings can’t be multiplied; one operand ha
to be an integer value.
7.6.3 Membership Operators
Python offers two membership operators for checking whether a particular character exists
the given string or not. These operators are ‘in’ and ‘not in’
‘in’ operator: It returns true if a character/substring exists in the given string.
not
operator: It returns true if a character/substring does not exist in the given string.
To use membership operator in strings, it is required that both the operands used should be
of string type, i.e.
in
not in
WY in "Hello
True
False
>>> 'HEL' in ‘Hello! ~
False
>>> ty! not in 'Hello!
True
>>> 'H' not in "Hellot |
False j
jello
in
Python being case-sensitive
>>> strl="ny"
>>> string='my book’
>>> strl in string
True
CCTM:TTo Use’membership operator in stings, its required that both the operands uuea should Bee.
string type.
7.6.4 Comparison Operators
You can use relational/comparison operators (>, tiet
aise
>>> "Eree" I= "freedom"
True
>>> "arrow" > “aron"
Tre
>>> "right" >= "left"
True
>>> "teeth" >> "yellow" >> “abet > 0H
True
In all the above examples, Python compares using values (called Ordinal Values). For most
common characters, the ASCII and Unicode values are same. The table below gives the most
common characters and their ordinal values:
Table 7.1: Common Characters and their Ordinal Values
Ordinal Values
Characters I
79 to 19"
"to ‘2!
to
v3
= a al
TM: Python compares two strings character by character according to their Unicode values, until it
Finds elements that differ. Subsequent elements are not considered.
185 String Slicing favsuring Te nothing buts sabeetee tral
Slicing j i set of values. A slice of a string is nothing but a substring. This
tracted sate ne F eraetas| slice. Chunk of characters can be extracted from a string using
Slice operator with two indices in square brackets separated by colon ([:]). The syntax is:
Here end is excluded
Strings In Pythonby returning charteters falling between the
Stary
h
ation through examples
Python will return a stice of the string
position till end=1, Let us understa s
» shows a string
code show Me having ait y
first line of the
Example 1: Consider the given code, the
alphabets in the uppercase.
alphabet_string = “ABCDES
sliced_string = alphabet_s!
tring (6:15:21)
print (alphabet_string)
print (sliced_string)
= 2a NS
Tas e eee ee
2[xTe[u[nfofrfopris{t w]x]y[z
alphabet string
The second statement is going to extract a slice out of this particular string startin
from the 6" position and points to 14" position instead of 15" position as shown below,
‘alphabet_string = TIKLMNOPQRSTUVWXY 2
sliced_string = alphabet_string[
print (alphabet_string)
print (sliced_string)
pins 3 ss JN Bes ey 20
(aoe eRE DE sol [eles pee
alphabet_string
>>> |
er C:/Users/preeti/AppData_
ABCDEFGHIJKLMNOPORSTUVEXY2
GHIJKLMNO |
Fig. 7.5(a): String Slicing Using Step Value as)
‘end’ position is to be excluded. Step 1 ensures that all characters from index position 6°!"
Position 14% are sliced out. Hence, statements 3 and 4 shall give the output as GHIJKLMN 7
In case the step value is taken as 2 as shown in Fig, 7.6(b)
extracting a substring starting from 6" position to 14%
element since step value is 2.
n Wy
the output shall be obtained
Position but skipping the adi#©
Ed
&
2
rs
2
=
8
8
5
a
5
B
éfae_(3RFermat Run Options Window
alphabet_string = “apcpsrciigia iShGRSFUVERTE
shiced_string » atphabet_stringt¢ OnSTUVKYZ
print (alphabet_string) ~
print (sliced_string)
Zz
alphabet_string
Fig. 7.5(b): String Slicing Using Step Value as 2
ence, the output displayed is “GIKMO",
fuample 2: Consider the given string A = "SAVE MONEY":
String A s[altvTe MT O[N[E]Y
Positive Index olifz[3[a;sfe[7]|elo9
Negative Index =10| -9 [ -8 | -7 [-6 | -s [a | -3 [2 [1
Here, print statement prints the subscript starting from index 1 and ending before index 3,
soit will print AV (1* and 2" index).
OW »>a: 3)
‘save
Omitting the first index directs the Python interpreter to extract the substring till the second
index starting from the beginning, i., index 0.
(@ >a [32]
NEY"
Omitting the second index directs the Python interpreter to extract the substring till the end
of the string starting from 3" position.
@ >> t2y
VE MONEY*
Omitting both the indices directs the Python interpreter to extract the entire string starting
, 0m Otill the last index.
8) oa5
For negative indices, the Python interpreter counts from the right side (also shown above). |
Here, start index is -2, but end index is not given, so it will start printing from index -2 F&M
; Seen meals ES
2d will print all the characters till the end (~2 starting point till index ~1). =
s
fared
>(fF) >>> Atr=2)
"SAVE MON"
Omitting the first index direc
the beginning, Since the negative Index Indie
entire string except the fast two letters Is printer
pretorto start extracting Ihe Substring,
os slteing from the end Of he string
hy
the Python Inte
(g) >>> AL+:21
"SV OE!
‘This will print alternate character from the string.
Practical Implementation-3
Program to input name and print the pattern as pive'
(if name is ‘ANAND’),
A
AN
ANA
ANAN
ANAND
1 below using string slicing:
A prog. cleaner
Se ———
te te oe pane ind print the pattern 92 given Below usin
seine eUEteing: Me nace Ae 'ARMID'), output. should ber f
i
i |
mA
hoy
i
namesinput ("Enter any nano is
for 4 in_ range (0, Len (name) #11 RESTART: C2/Users/preeti
print (name(0%4)) siicing.py
Enter any nase: ANAND
7.7 STRINGS ARE IMMUTABLE
Strings are immutable means that the content of the string cannot be changed after it®
created. Let us understand the concept of immutability with the help of an example.
>o>stri='Student'
>>>strl(3]="P'
TypeError: ‘str1 object does not support item assignment.
Python does not allow the programmer to change a character in a string. As shown in the 0%
example, str1 has the value ‘Student. An attempt to replace ‘d’ in the string by ‘p’ disp!"
TypeEtror.
TIM Sirings are immutable, ie, once created, strings cannot be changed. ;
ES atlSTRING METHODS AND BUILT-IN FUNCTIONS
“non provides several built-in functions a
sto easily modify and manipulate strings.
“efor on elements of a string in our code,
«redefined in Python programming langua
sing, object functionName()
tetus understand these methods,
We can think of functions as being actions that we
Built-in functions/string manipulation functions are
'ge and are readily available for use. The syntax is:
1, len()—This method returns the length of the string,
syntax:
len(str)
Here str is the string,
For example,
>>> word='Good Morning’
>>> len (word)
12 f
>>> stri='This is Meera\'é pen!
>> len(strl)
19
2. capitalize()—This method returns the exact copy of the string with the first letter in
uppercase.
Syntax:
str.capitalize()
Here str is the string.
For example,
>>> stri=!welcome'
>>> strl capitalize ()
"elcome!
>>> stri='Welcome'
>>> stri.capitalize() ;
"Welcome" — a
Pract
‘actical Implementation-4
“te a program to accept a string (a sentence) and return a string having first letter of each
“ord in capital letter:
Stee
Fed stri.split()
for 320 TE avcapitanizeoe* *
print (str2)
IAL
@
s
FS
S
ts
3
S
S
CAEd
S
ra
=
=
a
oo
&
5
3
4. replace()—This function reptaces all the occurrences ofthe olds
tm tak er Bo ad = usc v.1900 32 bit (In |
fvenon aiecs”qbesrcuncousabl, tar 2 2018, 16107840) (HEC 9-19
tei} on wins? for sore information.
fp Seloe, sree or “cee”
P= RESTART: C2\CHAPTER 6\PFO"_2-PY
ingest bn ately pyeten
Liga Seg te Ste? hton
sete nt lek
split()—The split() method breaks up a string at the specified separator and returns aj,
of substrings,
Syntax:
str.split((separator, [maxsplit]])
The split() method takes a maximum of 2 parameters:
+ separator (optional)—The separator is a delimiter. The string splits at the specifi
separator. If the separator is not specified, any whitespace (space, newline, etc
string is a separator.
+ maxsplit (optional)—The maxsplit defines the maximum number of splits. The defauk
value of maxsplit is -1, which means no limit on the number of splits.
For example,
seoeaseeesusnecoccosccaccos= RESTART? Shell
o> x "blues redigreen’
Doo xesplit("")
(blue', *zed", 'green')
de> texte'Love’ your country"
>>> print (text .split())
['tove', your", ‘country')
Here, separator is not specified, so by default, space is a string separator
The second argument ‘maxsplit’ is optional and its default value is zero.
Ifan integer valu
‘n’ is given for the second argument, the string is split into ‘n+ string
S.
os foceng: eine
va)
(thet "raluerysorenges ink}
>e>' print grocery. split(':"s3}) tnaxspiit de
URed', ‘Blt range: Pink") ae
P35‘ print grocery. 9p1it(:",5))
('Red', Blue’, Yoranges, dane)
237 pelaetoroctey-spLHEC:',0) teaxspiit $5 0, a0 it w |
Syntax: str. replace (old, new)
= 4 3tring example
33> print (stel replace (25, s32721°
FFhwae was 2 stting example
op strae “cole correc
35> print (str2-replace(‘co1g", +
hot coffee!
not")s, find()—This function ts used to se.
string. The find() method retur
given string. If the
rch the first occurrence of the substring, in the given
Ns the lowest index of the substring if it Is found in the
ubstring is not foun
str.find (sub, start, end)
na iss
Here,
sub:is the substring which needs to be searched in the given string
start starting position where substring is to be checked within the string
end: end position is the index of the last value for specified range
>>> word = “Green covolution®
23> results word.tind('Grcen')
2> print tresuity
>>> result word.find('green')
>>> print (result)
oy
>>> resulteword.tind("e", 4)
>>> print eauity
>>> resultevord.find(en",5)
>>> print (result)
a
>>> rosult-word.find('o', 11,14) #Finding letter ‘0!
>>> print (result) # trom 1ith to 1én position
a
Inthe last statement, letter ‘o’ is to be searched for starting from 11" to 13" position (as index 14
‘sexcluded in search). Since ‘o’ lies at 14" position, it will result in an unsuccessful search and
shall return -1 as the output.
6 index()—This function is quite similar to find() function as it also searches the first
occurrence and returns the lowest index of the substring if it is found in the given string
but raises an exception if the substring is not present in the given string.
Syntax:
index (substring, start, end)
p> ste index('He110")
>> stri.index(*ni*)
Teaceback (most recent call last):
File "", line 1, in
str. index (*Hi")
Waluegrror: substring not found
Dos.
isalpha()—This function checks for alphabets in an inputted string, It returns True if the
string contains only letters, otherwise returns False.
Syntax:
str.isalpha()
>>> str = *Good"
>>> print (str. isalpha())
True
is present in the string,
Returns True as no special character or digi
322 stris"this is a string”
>>> ai
Fay goTint (str: -isalpha())
Returns False as the st
g contains spaces. Ke
5
5
fS
=
[
le
&
=
aComputer Science with Python-XI
10.
>o> strle*Working with «..Pythonl!™
>o> prant(str].isalpha())
False
cial characters and spaces
False as the string contains spe
Returns
Inum()—The isalnum() method returns True
alphabet letters (A-Z, a-z) and numbers (0-9).
ric: (space) ! # % & ? etc.
ifall the characters are alphanumerij,
ample of characters that are not alphanume
syntax:
string.isalnum()
For example,
I
Ix = texti.isalnum()
FE
|prine oo
RESTART: C:/Users/preeti|
tunc.py
False
The above function shall return output as False since the text contains space also.
pREL= "Pythons
texti.isalnum()
[print (x)
RESTART: c:/Users/preetil
tone-py
As is evident from the second example, the output returned is True since text includes
only text and numbers.
isdigit()—This function returns True if the string contains only digits, otherwise False
Syntax: str.isdigit()
>>> str = "123456"
>>> print (str1.isdigit ())
True
Returns True as the string contains only digits.
>>> str] = "Ram bagged 1st position"
>>> print (str1 isdigit (1)
false
Returns False because apart from digits the string contains letters and spaces
title()—This function returns the string with first lette
in
T of eve in the string
uppercase and rest in lowercase. ry word in tl
Syntax: str.title()
>>> strl = “hello ITS all about sTRINGs! 1+
>>> stri.title()
‘Hello Its All About Strings!!*
>>>
itle() returns a version of the string where each yw a
; ch word is title-ca
cased.count()—This function returns num
trove do not give start index
at length of the string,
nber of ti
and end index
wh
mes substring str occurs in the given ae
then searching starts from index 0 and en
gmtax: Str count (substring,
tri = Kelle World! Helte Keltor
tr1.count ("Hello*, 12, 25)
Start, end)
Sov stei.count (‘He110")
Jower()—This function cony
erts all the uppercase letters in the string into lowercase.
gyntax: Str. lower ()
go> strl= "Learning pytkox=
p> print (strl.lover())
| earning python
ee gob Wlowerense i Mesa nlone ¢ ett oil simply
return the string.
ooo strl= "learning python"
>>> print (strilower ())
learning python
13. islower().
Syntax:
—This function returns True if all the letters in the string are in lowercase.
>> strl =
oe print (strl.islower())
14. upper()
This function converts lowercase leters in the string into uppercase,
Syntax:
str.upper ()
3? varie thelcone!
222 Faint (war upper ())
coe
already in uppercase, then it will simply return the string.
B23 Yaris sezcoue
- Print (vari upper or
ico
‘supper()
S
}—This function returns True if the string is in uppercase,
yatax:
Str. isupper()
>>> Strle =; -
= 7
SrgPESRE (Stet supper 0)
>> stereo.
>> stone
ry Pet str sisupper ())
_ PAL
A
Ss
=
SS
3
=
a
&
=after removing the space(s) from the Lf ory,
16, Istrip() This function returns the sti
string.
Syntax:
stristripQ
or
str.lstrip(chars)
chars (optional)—a string specifying the set of characters to be removed from the left, 4
combinations of characters in the chars argument are removed from the left of the string
until left character of the string mismatches.
>>> strl= "Green Revolution"
>>> print (stri.1strip())
Green Revolution
Here no argument is given, hence, it removed all leading whitespaces from the left of the
string.
>>> str2= "Green Revolution”
>>> print (str2.1strip("Gr"))
een Revolution
>>> str2= "Green Revolution"
>>> print (str2.1strip("rs"))
een Revolution
Here, all elements of the given argument are matched with left of the str2 and, if found, are
removed.
Practical Implementation-5
Write a program that reads a line and prints its frequency chart like,
+ Number of uppercase letters
+ Number of lowercase letters
+ Number of alphabets
+ Number of digits
line = input “enter a line
Jowercount = uppercount = 0
digicount = alphacount = 0
for a in line:
if asislower():
jowercount += 1
e1i¢ a.dsupper():
uppercount += 1
elit avisdigit(Q):
‘digicount += 1
if a.isalpna():
‘Alphacount += 1
print ("wunber of uppercase letters
Print ("Number of lowercase letter:
print ("Number of alphabets:
UbPezcount)
o¥ercoun
'» alphacount) mat)
Print ("Humber of digits:", digieounty
Cea eee oieBem Ctr al
Enter a line:Python for BIG data |
unbor of upporcase letters: §° -°2> |
umber of lowercase Letterss 4S |
urber of alphabets: 16
Nunber of digits: 4
17. rsteip(—This function removes all the tr
Syntax:
estrip( @
or
ailing whitespaces from the right of the string.
str.rstrip (chars)
chars {optional} —a string specifying the set of characters to be removed from the right.
alleombinations of characters in the chars argument are removed from the right of the string
until the right character of the string mismatches,
>>> strl= "Green Revolution
>>> print (str1.rstrip())
Green Revolution
Here, no argument is given, hence, it removed all leading whitespaces from the right of
the string.
>>> strl= "computers"
>>> print (strl.rstrip("rs"))
Compute
Here, the letters ‘rs’ are passed as an argument; it is matched from the right of the string and
Temoved from the right of the str.
18. strip()—This function returns the string after removing the spaces both on the left and
the right of the string.
Syntax:
str.strip()
>>> strl =" Hello ITS all about STRINGs!! —*
>> stri.strip()
‘Hello ITs all about STRINGS!!"
>>
19, isspace()—This function returns True if the string contains only whitespace characters,
otherwise returns False.
Syntax;
str.isspace()
>> stries #
?>> print (str1.isspace ())
True
>> ateter —eython" 5
yyehion =
>> print, i ” =
raise nt (str1,isspace ( =
, . a.
20. istite—the itite() function doestt take any arguments. returns True ifthe string
'S properly “ritle-cased’, else returns False if the string isnot a "title-cased” string or an gk
Empty string. a
basynta | :
str. istitlea | ;
>>> print (ste istitied)} | H
|
39> 30 TALL Learn python* |
d>> print (s.istitied)) |
False |
be ee tihis ts ¢ spor" |
2 35> print(s.istitied)
& Tree |
2>> ge “pyTHON
25> print(s.istitze())
False
21. join(sequence)—This function returns a string in which the string elements have bee,
joined by a str .
i ya string separator: 24.
syntax:
str. join(sequence)
Sequence—Join() takes an argument which is of sequence data type, capable of returning
its element one at a time. This method returns a string which is the concatenation of eat
element of the string and the string separator between each element of the string.
b> stete 112045" de> strde ‘abcd!
do gett 33> ante"
3>> s.join(stri) S55 sjoin(ste2) .
Srasdea-5" ‘anoecea! -
22. swapcase()—This function converts and returns all uppercase characters into lowercase
and vice versa of the given string. It does not take any argument.
str.swapcase ()
The swapcase() function returns a string with all the cases changed.
>>> stri= “Welcome”
>o>_strl.swapease ()
"WELCOME |
>>> str2= "PYTHON"
35>. str2.swapcase ()
“python!
ob> se "pYThox™
>>> s.swapcase()
"pytion"
23. partition(Separator)—Partition function is used to s
specified separator and return a tuple with three parts:
+ substring before the separator;
plit the given string using
+ separator itself;
+ a substring after the separator.
Syntax:
str.partition (Separator)
Separator: This argument is required to separate a strin
returns the string itself followed by two empty strings
poe str3e ‘xyztoma:
33> stra-partition(
Cayzigeail.cost,
it
18. If the separator is not foun
within parentheses as tuple-
EU) TAS CurE A TUla ule.sere, Separator IS NOL FOUN, So returns
eae *Hardvortpays
op ee erate)
» fork", "pays')
Here, sv parts:
1) substring before separator, ie,
Tuard"y
eparated in three
2) separator itself, i,
‘work’, and
3) substring part after separator
o>> sted ste2.partition(:
>>> print (stra)
Cardworkpays', +4, +4)
“y
>>> strS= str3.partition(+0+)
>>> print (str5)
xyz") 0, "gmat com)
24, endswith()—This function returns True if the given string ends with the specified
substring, else returns False,
Syntax:
str.endswidth (substr)
foe ae*areiicial teelivgence™
b> avendswith( Intelligence!)
‘Teue
‘bop avendswith (artificial)
‘ralse
25, startswith()—This function returns True if the given string starts with the specified
substring, else returns False.
Syntax:
str.startswith (substr)
>>> be'Nachine Learning”
do> bystartswith ("Mac")
‘True
>>> b.startswith(*learning')
False
Above functions in a Nutshell:
>>> “Hello World” upper () . Lower ()
‘hello world"
>>> "ello World". lower () «upper ()
"HELLO WORLD?
P2> Helo Worle tind(wor", 146)
> “Helio World". find ("vor")
>>> "Hello World® .isalpha()
Ee r1d* Asalphé
>>> “uelio worte".tsalnun()
Fatse
>> “123¢" tsdigit
Tee oe
335 s12n¢9"
22, 1am saaigit 0
Pag Het© World” endsvitn("Wor}6")
D> 7 ep"
Trae Bete Worta* vendawients10")
Rise
Trae Helle World® startswith("#e120")
Rello Wort” endswith ("Wor")
he string itself, followed by two empty strings.
‘Hard’,
@
Strings in Python7.9 OTHER FUNCTIONS
; ors are stored in intege
In internal storage or memory of the computer, the charact peciinas The integer vat.
A specific value is used for a given character and It [s based on ASCH ¢¢ here are differ,
numbers assigned to capital letters and small letters
n and chr
Python provides two functions for character encodings ord() and chr)
ord()—This function returns the ASCH/Unicode
ds che tht
>>> ord(ch)
98
>>> ord ("A")
65
(Ordinal) of the character.
© chr()—This function returns the character represented by the inputted Unicode/Ascy
number.
>>> chr (97)
tae
>>> chr (66)
tpt
R snemone BYTES
> Asstring is a sequence of characters.
> We can create them simply by enclosing characters in quotes (single, double or triple).
> Positive subscript helps in accessing the string from the beginning.
> Negative subscript helps in accessing the string from the end,
> ‘+! operator joins or concatenates the strings on both sides of the operator.
‘The * operator creates a new string concatenating multiple copies of the same string.
Operator ‘in’ returns true if a character exists in the given string.
Operator ‘not in’ returns true if a character does not exist in the given string,
Range Slice gives the characters from the given range using
You can use relational operators (>, ) to compare two strings.
Python compares two strings character by character according to their ASCII values.
steings are immutable means that the content of the string cannot be changed after it has been created
There are many built-in functions for working with strings in Python,
Python provides various string functions like len(), capitalize(), find(), ete
split() method returns a list of all words inthe string using sep as the delimiter string,
uppert) method returns a copy of the string converted into uppercase characters,
{sdigit() method returns True if all the characters in the string are digits, otherwise returns False.
count()function will return the total count of a given element in a string
index{) function returns index position of substring
strip() function performs both Istrip() and rsteip() on string,
Computer Science with Python-XI| pieeTIVETYPE QUESTIONS
, SSS
s.fillin the blanks
fa) Astring is @ Of characters,
ss ~~ Subscript helps in accessing the string from the beginning,
ee + SUBSCTIpt helps in
accessing the string from the end.
- the strings on both sides of the operator.
~ method returns the lowest index ofthe substring I itis found in the given
{a) ‘¥ operator ..
(e) The
string,
(f) vsesmnnnnnnnnen FUNERION returns the exact co
PY Of the string with the first letter in uppercase
{g) Strings cannot be modified as they are .,
° : soe data types.
(h) The sequential accessing of each of the elements in a string is called string
fi)
~ “membership operator returns True if a character or substring exists in given
string
0 a
(i) find() function returns
(se
(m) «
An) ssessstssetseen
returns False.
$9 Part of the string containing some contiguous characters from the string.
when substring is not found in the main string.
est index of the substring if itis found in a given string,
method returns the low:
~ function is used to count how many times an element has occurred in a list.
~ function returns True ifthe given string starts with the specified substring, else
2, State whether the following statements are True or False.
{a) An empty string is a string that has zero number of characters.
(b) The last index number of string is length-1 or -1.
(¢) “abe” * 2 will give abc*2 as output.
(d) Multiplication operator (*) replicates the string.
{e) We can combine two strings with the help of & operator.
(1) When we compare “A” != "a", it will give True as an output.
(3) String allows forward and backward type of indexing.
(h) In Python, asc() function returns corresponding Unicode value of a character.
(i) Size of \\" is 2.
() Multiple tine string created with the help of triple quotes will include end line character in the length.
(ky Astring is a mutable sequence of one or more characters
3. Multiple Choice Questions (MCQs)
{a} Which of the following is not a Python legal string operation?
(i) ‘abe’ + ‘abe" (ii) ‘abe’ *3. (iii) ‘abe’ +3 (iv) ‘abe’tower( )
(6) In Python, string + and * represents which of the following operations? =
(i) Concatenation, Replication (ii) Addition, eae
(iii) Neither (a) nor (b) a Both (a) and (b)
(€) Which of following is not a valid string operation?
(i) Slicing i Concatenation (iii) Repetition (iv) Floor
“ i 2
(4) How many times is the word “Python” printed in the following statement:
$= ‘I love Python’
for ch in s{3:8):
) time 8 times (ii) 3 times (iv) Stimes
es
£9) whi rect syntax of String Slicing?
Which of the following is the correct sy (i) String name(start : step)
: end
() String name[start : end] (iv) String_name (step
Mi) String name(step + endl
Ss
c=
a
i
A
&
=
a
start] aaracters of “Digital India”
(1) Whatis the correct Python code to display the last four characte " °
W) stri-a w) ote (asl (wy mer (eas (1 stetia;
{e) What will be the output of the following code?
strl= “Hove Python.”
strlen = ten(stet)
print(strlen)
oo (i) 29 (ii) 24 uae
(h) What will be the output of the following code?
Strl= ‘My name is digital’
‘Str2=Ste1[3:7]
strlen = len(Str2)
print(strlen)
(ya (ii) 14 (ii) 24 iv) 34
(i) Which method removes all the trailing whitespaces from the right of the string?
(i) tolower() (ii) upper() Istrip() (iv) rstript)
(i) To concatenate means to
(rey (ii) join (ii) split (iv) mattiply
() function will always return tuple of 3 elements.
(i) index() (ii) split() partition() (iv) strip()
(I) What will be the output of the following code?
A="Virtual Reality’
A.replace('Virtual', 'Augmented')
(i) Virtual Augmented (ii) Reality Augmented
Augmented Virtual liv) Augmented Reality
(m) What will be the output of the following?
print ("ComputerScience".split ("ex",2))
(i) ("Computer", "Science"] (ii) ("Comput", "Science"]
(ii) ("comput", "erScience"} (iv) [*Comput", "ex", "Science"]
SOLVED QUESTIONS ===
1. What is a string?
‘Ans. A string is a sequence of characters where each character can be a letter, number or special symbol Wé
can enclose characters in quotes (single, double or triple).
2, What is slicing in string?
‘Ans. Slicing returns the substring from the gi
n string using slicing operator [:
3. What is traversing a string?
‘Ans. Traversing a string means accessing each character one after the other by iterating through the elem
of a string using either for or while loop.
Write the output of the following statement:
strl = ‘This is Nohit\'s "CS" book"
print (len(str1))
‘Ans. 25
. Consider the string str="Green Revolution”. Write sta ing
Fy ro display the last four eharacters. ements in Python to implement the follow’
(6) To display the starting index for the substring ‘vo’,
(c) To check whether the string contains ‘vol’ or not,
(d) To repeat the string 3 times.
nce with Python-X1str (-43)
pw reion"
r.find("vo")
‘in str
true
qa) str"? .
sgreen Revolution Green Revo}
«what willbe the output of the following programmin
yenamaZing™
print (x(381,"and",x(32])
int (21772) ,"and", x(-4:-2})
print (x(2:7], "and", x{-4:-1])
1g code?
ing and Art
Me ading and 24
ating and Zin
1. Consider the following code:
stal=input ("Enter @ string:")
while Len (STR1) <: if stri elif in stri: not int str="E" else: strisstri print what will be the output produced input is: tbzz abed bec endless loop because always remain at index write of following code when executed: dslen ntext="
for iin range (0,1):
if Text [i] .isupper():
ntextentext+Text [i] loner ()
elif Text [i] .isalpha (I+
ntext-ntext+Text [i] upper ()
else:
ntext=ntext+'bb" printintext s statement many times is word python rocks ch prine pane ms syetehedto bh strings find following: ans. output: how can you create an empty string created by using either double quotes or single and assigning yeni toavariable. i differentiate between indexing traversing string. indexing: accessing individual characters subscript value cae: indexing. specifies character to accessed written square brackets traversing: each one after other iterating through elements a sting for while loop. why immutable data type contents cannot changed it has been that immutate type. example ste1='Sound’
Stri[0]="?"
would result in — TypeError: ‘str’ object does not support item assignment.
414. A string called str contains whitespaces at the left of the string as given.
str=" Python Program"
Write the command to delete the spaces.
‘Ans. The commandis:str-1strip()
115, What will be the value stored in bval upon execution if two strings str1 and str2 are taken as “Delhi”
“New Delhi"?
(i) bval = stri > str2 (i) bval = stri.lower() < str?
Ans. (i) False (ii) False
16. Write a Python code to access each character, one by one, of string ‘hello’,
Ans. for ch in thello
print (ch)
Output:
h
e
1
1
°
17, Write a program to count the number of vowels inthe string ‘pineapple’.
‘Ans. Code:
word = ‘pineapple’
count = 0
for letter in word:
if letter in ("i' tat countscount stone computer science with python-xi wnat willbe pro we pandarlol ntr range strli supper row nstr strtiy fam shipper slower ays andariel program: stre digital india .upper en: ini program check whether palindrome not. code: string: islen pel-1 p="p-1" break reads line then counts words displays are there cod line: split cate x: cnteente1 ffint eye every letter inthe te printsa ca e.g. school becomes school. length="len(string)" string2 ab2nm stringlal upper ho count. nter str2 lestrl.split ent="0" lr iesstr cnttel appearing: function vowcount which takes as argument should cou display occurrence starting vowel given example: content follows: updated information simplified official websites. ww substring appears they def cent="0" word: if0jin entt="1" cnt longest maxiength="0" maxword="" x="len(i)" sf>maxlength and i.isalpha()==True:
print (i)
maxlength=x
maxwor
print ("Substring with maximum length is:*,maxword)
(CCEA ua TueUoutput:
enter 2 sting:Hello Python
ello
python
string with maximum length iss
sgt a program {0 remove Vowels from a string,
gerivinput ("Enter string:")
Python,
i in range(len(str1));
if strl[i] not in “ieouaaoruen:
str2= str2+stri(i]
print ("Original strin.
SretNew string ie
‘output:
original string
new string is
We are learning python"
r lrnng pythn”
27. What will be the output of the following program?
res] = ("SKy"]
res2 = ("TRE")
nes} = ["LiMIT"]
11 = lentmesi)
12 = len(mes2)
13 = len(mes3)
n= 11412413
for C in range(1,n):
if (C84 == 0):
print (mes2)
12-12-12
else:
if (C83 == 0):
print (mes1)
qe i-1
else:
print (mes3)
3-13-11
Ms (Linrty
(tinerey
Write a program to input a string having some cigits and return the sum of digits present in this string.
"ainput ("Enter a string with digit:
0
for iin a:
Af Lisdigit:
c nt (i)
Print (cy
"Find the output of the following code:
S*"Vow Python
Print (len (s))
fag gS O18 f-11)
He
a
5
=
ES
iS
3
cHUNSOLVED GUESTIOnS SS
1. How does * operator behave on strings?
2. Explain function split() with an example.
3. How many times is the word ‘HELLO’ printed In th
python rock:
for ch ins:
print ("ilello")
Write the output of the following:
>>> x="hello”
>>> print (x[1:-2])
5. Write the output of the following:
1¢ following statement?
(a) string = "Hello Madam, I love Tutorials"
substring = "Madam"
if string. find (substring)
Print ("Python found the substring! ")
else:
print ("Python did NOT find the substring
(b) 5 = "Strings in Python"
print (s.capitalize())
print(s.title())
86-s.replace("in", “data type")
print (s6)
6. Find the output of the following:
word = "work hard"
result = word. find ("work")
print (Substring, ‘work", found at inde:
result = word. find(*har')
print ("Substring, ‘har ' ,found at index:", result )
result )
Af (word. find(*pawan') !=-1):
print ("Contains given substring ")
else:
print("Doesn't contain given substring")
7. Consider the foll mySubject:
mySubject = "Computer Science"
What will be the output of the following string operations?
{i) print (mySubject [0: len (mySubject) })
(ii) print (mySubject [-7:-1])
(iil) print (mySubject (::2))
(iv) print (mySubject [1en (mySubject)-1])
(v) print (2*mySubject)
(vi) print (mySubject (::-2))
(vii) print (mySubject (:3] + mySubject(3:])
(viii) print (mySubject . swapcase())
(ix) print (mySubject.startswith(*Comp*y)
(x) print (mySubject.isalpha())
8, Write the Python statement and the output for the following:
(a) Find the third occurrence of “e’ in ‘sequence’.
(b) Change the case of each letter in string ‘FuNcTion’,
(c) Whether ‘Z’ exists in string ‘School’ or not.
Fa
5
=
=
8
a
3
BA
A
ce4. comiget the ting ste =“Globa Warming
wate statements in Python to implement the f
{a} To display the last four characters,
io} To replace all the occurrences of letter
ollowing;
“an the string with **",
sp wate the outPut of the following program code
- vi
vvirus-virus!
tt
["Fundamentals", “og,
= "" #no space
int (al. join(str))
Python" |
11, What will be the output of the following code?
qext_ = "Mind@Work!"
= len (Text)
atest
ri in range(0,1n):
£ Text (i].isupper(
aText = nText + Text [i] lower ()
elif Text {i].isalpha():
aText = nText + Text(i) .upper()
else:
nText = nText +
print (nText)
12. Input the string ‘My School’, Write a script to partition the string at the occurrence of letter ‘h’ .
13. Write a program to convert a string with more than one word into titlecase string where string is passed
‘as parameter. (Titlecase means that the first letter of each word is capitalized.)
14. Write a program that takes a sentence as an input parameter where each word in the sentence is
separated by a space. The function should replace each blank with a hyphen and then return the modified
sentence.
15. Write a script to partition the string ‘INSTITUTE’ at the occurrence of letter ‘T’.
16. What will be the output of the following programming code?
stre"My Python Programming
print (str((-5:-H)
print(str(1:5))
print(str(:-4))
print (ste[0:1)
print (str(:13-4])
print (str(:3])
17, Write a program to count the number of each vowel in a given
18, Write a program that reads a line, then counts how many times the word "s' appears in the line and
displays the count.
18. Write a program to remove ‘(if any) from a string,
string.
CASE-BASED/SOURCE-BASED INTEGRATED QUESTIONS
js a company that deals in maintaining the phone numbers of
1 AB i Ud.
Bialing pNetweris Eve * code automaticaly at the time of adding the phone number in
Customers globally. It prefixes the are
its database. £10 digits and two dashes, a dash each aft
wi for a phone number of 10 digits a a dash each after area
ite @ program that prompts for 2 P yrample, 017-555-1212 is a legal input. Display if the phone
code a umbers. For €
Gigits and dashes at specific places):
A
A
=
ts
IS
a
Sy
tAAns. ae
EAT ASDSHAR ROTC TAT ONTY
EST Aeon ne
fu ta tom hee Qe Wee 0 —
‘code for adding phone nusbers in the proper COrmat
[P stnpue (tater shone wusber 1")
Weagth Bust be 32
Se Tentpy Sand
Tepe
val =
Le vats
EINE (py"is voniay
otset
Print ip, "is Lavalier)
RESTART: C:/Users/preeti/appData/Local/
casestudy1.
223098888 is invalid
333) |
RESTART: C:/Users/preeti/AppData/Local/
casestudy1.py |
Enter Phone Number :989-234-3377
989-234-3377 is valid |
2, Kids Elementary Technolo,
ies help nursery children to improve their handwriting and writing skills sus
as word formation,
‘recognition of lower and uppercase letters and small sentences formation.
Write a program that should prompt the child to type some sentence(s) followed by “enter”. It shoul
then print the original sentence(s) and the following statistics relating to the sentence(:
+ Number of words
‘+ Number of characters (includin
+ Percentage of characters that
ig white-space and punctuation)
are alphanumeric
Ans.
Gr Rte GOR TR RS
(64 tem Ton Optom inion hep Rares
3 = input (“enter a sentence 7 >
number of words = 1
Rusber“of"characters = ten(s)
3
it ftsaimung
aun
Sere a tytnet® iS a space means there
‘6 fumber_of words += 1 ne bad
print ("rusher f Tords ace muaber of vords)
PEIRE (ounbes_of characters’ sre snieegee ra
Hest percentage ot casaccers thaw are SERAEASES®)
another word
+81_nu2*100/16n(s),
Enter a sentence :
nunber of words are
‘Rusber_of,
DTU Ce aur Rol LU Dec