0% found this document useful (0 votes)
17 views15 pages

Strings - 1

Uploaded by

Shri Jr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views15 pages

Strings - 1

Uploaded by

Shri Jr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CHAPTER Strings and Regular

12
Expressions

string object
in Python ne ord
the handling
of
at
strings
sn s
an be handled wingular expre
elaborates on

his chapter tterns efficient y


effceny
Other Tthan ordinary str
string value. handle text patterns
epressions are used to

of String objects
The character data is also coa
12.1 Methods
data type
is po characto defined with single quore ute
InP'ython ing. there
h size 1 The t atacan

hello

heno
eiat

>>>type(D)
cclass ' s t

wntt
anc starts

accessed with the index


can be
ng content

al0:2

lo

cannot be deleted. lawever, the cotnpiete strin8 0oject can be delte h


3 1he elements of a string
using de kyOra
> a w t h i S Is. strine

this strin

del(a[o)
TracebacK
Frlecstdin>, ne cmouue
tings and Regular Expressions 2

1ypeerror:'str object doesnt support item


Jel a doinon

cent cN last
NameError: nam smodule
not oefined
ce operators useed to extract the
of the string and the length should be specifed characters in the
the input
input string
string For
For this,
his, the starting p o s n

>st='a
5 st
abod

st03
abc
Two strngs can De
concatenated by using"-" operator. The operator is used to
rept
as'go0d
orning
good

goodmorning
dsa2

oood

Two

strings c a n be concatenated by placing the strings together. They can also be


parenthesis, In these case B a na onnst n the current statement comubtee
only
y ng

Koodmorning

morning)
Soomoing

n a
string object, the index and
the character sgven as a pair by the enumerate() method.
Output

nonroEramsoython alPY
is ts a
pre prg
auinputt"Enter tho input string) this is a

uneratetaj t . 12%.3.s.(4. .
Pinfa)
26, S1 , (8, a1, (9,*9
printb) (10 p,11, Th012, 'N
S0 Python Programming

T h e len0 returns the length o the object


>an g0od morning

Kood morning
» lena,

12
below.
listed method.
are italize
methods
with capitalizeU
Varlous ring capitalized

The strin ldcter


is

'Go0d orning
at the center
in he
Presicribed width
* h e centerð methof will place the mplat string

norn
go00nter(15)
good imorning

the frequency
0ccurrence
ot tne nput substrn
method is used to count
*
he counto
nput string

good mornin
.counO

will check whel her the inplu ung


o witn tne input substiqge
*
The endswitho function

good morn
>»A.Andswitn(ng)

True

checks whether all the characters in the strlng are empty or not Fay
The isalpha0 method 5 not an
aiphabet,
tALSL,
OtherwISe it refiurns TRIE
then t returns

De ar tne Characte

good mari
>R.isalpha
hai
2 bisalphal
Truo

Theisdecimalmethod returis RE If all the characters in the string are decina, ote
t returnsF'ALSE.
91=100
oo zisdecimal)
Irue
Expressions
ngs arnid Regular
1ehe isloweroe
methOd r or not the all ch
ase r not. checKS wlhether all chara
not all
Tor or not ne nput string in upp are

eharactet.
e n the input string are

qe ABC
Tue
QisGOBr
ves
alse
wi
The will return
ill return the
the string with al
string the lower case letters, whereas the
uppaz
wth all the upper Case s

owerd
ibe

w.upporg

artitiona
erforneu
etnodwill partition the input string into varlous Pars
parts, The partition is
aceo 8 ne
Bubstring
»uthis is a
program
this is a
program

>aapartitionrs
thE. 9 s a
program
he
swapcase) method
wil return the string by swapping lower
case to lower case. case to
uppercase and
upP
case
>>>t=ABodEFgh

aed
abCDefGHH

12.1.1 Escape sequencing


The escape sequencing is
character
used to represent speclal in
upports escape sequencng Various characters used tor escape sequencing ae ahsted pclow characteTs strny
In
the string " can be
representod with
"
n> line 1
aab
A

yntaxtrror EOL while soanning string literal


ab\

>> lenta)
b
254 Python Programming

OUtput

ORSTUVwz
the value of letters stant
abedelghjidmnopgrstuvwxyzABCDErGHRMO

owecase oontanp I MNOPOHSTUVWXY2


The value of hexdigits oonstant: 012345879abadefABcOE
ooctd gits constant: 01235
nr9r0AAAi
-

The value of wi
vaam of printable constant:
ogheimnoparstuvwxyzABcDEFaHLDRLMRO wwA"Ne 0

n 3 , all these functions ate available as string metn unctlans in th


ui are isted below.
The startswitho method is used to check whether the g wtin te
input stringg or not. For this, the start and end index can atso Do p e w e methot

Output
DVPyth
thonPrO
Entar the input strine

enter tne subatring tO


De matchee
inpu Ente good is started in
goo
slwinoutecntee eteine to be matohed.)
aa.starswitng6) tring
enter the substrine to
elnie be matched
started in '. ) mor
se:

printis1is not stantno n a

The findometho pur bing. It the substrit


Isfound then the inev a rned

Output
D'NPythonPrograms>pythor
Eter the input string dood
o o marched:)
miormint
a-s.find(sl) entor the substring to
be matohed:
in , s. at a postion
prints1. 1s found mor is found in good morning at 5
tound in s ponition
printsl not
n e suostng n the gven stttng the
substring IS n o t tound, tnen an exception
Expressions235
Regular
trngsand

Dutput
o b2.py
pu st V utstring Eo00
pu
wiet morning
uate to
printtsl aption is found in eood mo E
arinttsl 1s notround in s) position

method returns the highest tndex in the mpul strIg


position of the ubtring
e ut
is not avallable
not in the Input stre
avallable ih
eirings
the ihplt Stang. heti W
Output
VthanPTogran5>pyncn pe9y

s he hstring te he r
he matched:) Enter the input stE
ndts1)
fiB-D
print(s ouno 8 MtA ponition)

Os n u p p y a t po
rintis is nat found ins

rindex) method 1s sinilar to rfind0 method. IF the substring is not available in a g e n

thEn rfindi) method will r e t u r n i w h e r e as the rindex) mettiod wil r o

Output
h o n D2 p y
0Pytho ringthis is
very good and is happy

din this is vory very Eo00


and is happy at 27

prirnttei s notfound in . ) pOsition

The isalnumnetbod
cnecks whether or
ot all characters in the input string afe
alpnanumet
retutns
the characters are
aphanumeric, Then it returns TRE otherwise, It
FALSt..
all
Output

mormin oo
s=input"Enter the input string All ths oharacters in the strind are
5aiun0 ot aiphanuiheio

printr'Al the oharacters in tie string are miphanunerio0

All the churacters in the string are


print All the oharantera n ho Bns
alphanumaric
pnanuneO7
36 Python Progranming
all the
characters m ny npa are digits
sicdga) methoid
returns TRU
e Then it refurma t A L S .
e h
are not dgits,
Output
ssinput Enter the nput strn
DPythonrom
Enter the input atring 4 y
m A the c h a r a c t e r n in the string a r o Al
the oharaclers n tha str
alse.
not digis7
PintrAl the characters in the string arm

TRUE when the lnpiut string


ts
aa at acter. f not,
miethod retiuns
he
isspace0
ts FALSE
Enter
the input Birng
Outpur
foe in rangeD lenis
ifsispaced y
Spoe I8 Availiable in nput strin morning
V
Spaco
finge-0 put atring
printi'Spaoe is not avaiana input string)

method returns the keft justilied lnput strng witnin


e
ied width lt can al
Tnebusto
he u d to gjustificatO
fill the empty poSa
Outpur

D:VPythonFrogra pyn b2y


=inpu dth to be justibed ' Fntee the width to be justliud7
to be T n d 7 Enter the caracter to i l e c a
=inputrEnter the oharucter
The left jusurioo
asustitu s
print The left Justitied strtne
The rusto method returns the right justit ied input striag within the specined width. lt ean a
use ilchard method to fil the empty poSufions ouring justca

Output
DVPythonPrograms>python ba2p
sinputrEnfer the mput sti Enter the
nput snnpo
h r e n t n e w a t h to D Justiedz
teintinpulrEntertnw
U=inputCnter theCharueto o t
EnEr
printhe r h t justttod atrine

zlo method extends the width ot the input string to the


specitied NZe
by placng o tn
he
the ernpy posatos

Output
DWyhoProuramspylnon bY
lnpad dth to tb afilled.
Enter the pur otE EO

zhiit Flod stringe 0008


printiThe zera fillod strin
Expressions
g and Regular
e r ) Tethoa ta
ractiers. atng
ng
uta the eqaivalent vtrng owerca
Output

Enter the r i t strine 90oD


pin

method d a
ing and returns ibe
chatae eqlyae string wn a
equlvalent
Output
yhornrogrmBpyinoao9y
rput En putrna)
cAse string= GO0
the Istripl0 hethod teturns the inpu n

avnp8 he specifled
character e
sito Charactet considerd 2
v a l ts wtntespace

Output
Gnrojgram ms»python ha

tEnter the input string)


nutiE
utEnter t e left chracter to be stripped)
Enter the eft
characte

print("the resuit of lstrip") f tstrip

he rstripn ms the input string by removing the specified character in the right
nosition ne detaut caltacter considered lor removal whitehpac

a
onPrograms>python 2py
the input string this
EDOo0ooddood
o be

tinpa a ppod
the renut ot r s t a p haE
the resut of rstrip
The stripl:0 method returns the input string by removtng the spectfied character in ether e

right positions. 1he detault character cosidered tor


or

removal 1s wepace
Output
OVythonPrograms>python b20y
Enter the input string this isE00
r n e onaracte o be s t p p e a

the resultot strip= his is good


DEPythonPrograms>python b2.py
Enter the inpit stnnE hsso
t strine 10 00
Entar the charaoter to be stripped) Enter the caracter
=sstripit) the rubultot strip this is goo
printi t h e result of
stripa0
238 Python Programming

h e maxo method returns the maximum element n the t e r a b i e g a e n t s .

Output
s(10.20.30,0,b0 DPYthonr python ta,
axis
PEtethe max rusultw
m u t e 50 2y

* h e ming method returns the minimum element in the t e r a n e a g u o n t s

OutP
mnr0,40.50 N 2
printrthe min resulte

T h e replaceömethod replaces the existing substring within the nput string with the
he ney

Output

onoBrams>pyth
Ent nput string this is

Enter
s=inputcEnter tho nput atinE the 8x0sng
ubstr
the result of strip= thean

E n
rpcoe
The title) method converts the first chiracter of each word in the input string to the up
CaBe character.

Output

Enter the
utEnter the input string) input stngthis is gDod
PFrinttheesult.fi0

The splito
Dased
mcthod splits the input string intobasea
on h e number of required ines or
various substrings he splitingcan be perform
on the a e n f e r
torpttng the string
Output
yinoo spyhon B2
Enter the
orintthe result= "sspl Ghe
rosuit Tun 0001

The joinomethod joins the two input strings. During the join operation, the first string will s
joined atter each character in the second string

Output

E t a e the d tine Enter the second strine pytho


n e rosu pabyioEapnaponn
printi'the resulta njoiniti)
essions
Stings and Regular

The isiden T when th strins

w b e retturned s a ldentifler. If the input


etifte

tifier0

Output
trine a dentitier)

input string in a identifier


printinpar n s 0 AJ0etifier

he ord) funethon tou n e ascll


cüde of the
inpu haracte
Output:
PythonProgranmspytnon
n b2 py
Enter the strint ND

The asol
code o
erintThe asai oode af,in"ord() The ancii oode of o is 99

hro runcton t e t u t
The
the equivalent character of the
Input ascit
co
Uput

on b2 py
Dyo
=intinput(Enter the asail code:
int("The oharactsr for the Oven asoi code of " is The charaoter for the wvon a s o

chris)

124 String Formatting


Similar to Frograrmming ython Programning also offers usage of various tormat
rifers arious to mat fe t e d tbelow.

The d is used tor tormatting the integor data

Output
DPythonPrograms>python al.pY
Enter intoger walun.
a=inttinputtEnter intoor value:
pneintegor value: Sd 96a) Integer value: 10

The s is used tor formatting the tloating point data.

Output
DVythonPrograms>pyhon a.Py

Floating Point value: 26.344000

The
S.csize>t is used to tormat the tloating with the fixed size ot fractional number.
Cab Python Progranan
a t W r i t e a l y t h o n p r o g r a n to remove tie d u f a t c 1n aqn lno

inpurEnter tho input E Dutpur


ueet)

for 1in
inot in du nornimk

print"The string withonut dun licates=

Program 13: Wrife a Python progtam to sorT.toe eeine


o
a sing
Output

0Vythtnrora pythe 2
lle
xjoinisorteds tring- ehlio rie
Printthe alphabetical order sorted stringe

Ogrom write a Python program ta renove nh a caraeters the input t

Outpu

DVython Saay
23de
printThe string with alphabatse

Program 5 : Wrile alython program lo o r e Tes i pEn n e amtinct leterk

Outpur

V ramspython t2
inpu tring
iaortodiatin lowurtl)
printa2)
rOgrom26w ayndpeogralnm o pr upotnue ns of a
s 0 gen sng

Output

from
OPythonProgrunoythan a2y
iterto0ls port F Enter the
The last or
pe
ermutationsirangel3
printThe Iiut of permutations ar0 13 121, (3, 2 11
prim

Program Write a y h o n program o prnt tne tuat non tepeating character i t the npt

Output
ho ling
pur r VyihonProgramepython Bzp
Enter tho Sn

countii ein
printr The firnt non repeatad cnHCTm tho r n g
the st
g and Regular Expressions

rite a

Python prugram. to
print the run length encodin
nputltnter he string7

inx
Outpan
rograms>python 02py

s+strkcounto Eeee the stringaaanbo0


rintor

af each
rom 19 to check whether the iput strings are anagranms
PrOg

intu Entr me it string Qutpur


econd
Enter
the slrnG D2-py

ortedix.upperd dyuppnr0
The two stNnE aro
anagrama) Enter the socond stringbo
print The wo strings are not anagrarns") w ingsaean

gram 20:Wrile atython program to print all the words in an input string&
Prog

Output
P r o p r a m 8 > p y t h o n b2 9

Eoar tha ntring hello good mo


o
=npuln nE1
he words in the input stineTneno
erint The words in the input o n o

pgrom 21: Write a yrhon progratn to remove the words beginninkWn o w

nputt Enter the stringE)

y spito
Output
on b2 py
tor
01 ynon apple is good fruit
0ot in [a,0,10U
good fruit

printiz)
With co1sonants
to fefnove the words Bbeginning
Program 22: Write à
tython program

inpull'Enter the strinE

Output
VythonPrograms>python b2 py

Ol in a':e,T.0 Enter an
the string appie 18 Kood Trut

zeit** an appie is
printz)
244 Python Programming
to c o n v e r t
the aecitnal
nuoer
to other formas
rogrom 3: Write a
Python program
Tormat) method
Output

DPythonProgrampyhon
Enter
lpy
the Decima vialue:100
asintinput("Enter the Decimal vau
)
Ene alValue 100au 58
slontdnputlentep the Fio a
Binary Value-1100100
printrBinary Valuee(0:b)format(a)) Ootal value1a

print('ootal Value-(0:0)" formata) Hexa DecCma yaue64


Input decimal tioat
printrHexa Decimal Values(0x)tormata rmattbi)
print(input decimal tloat valuos (tormat
valune 5.8000o0

Write a Python program to read the stting and


pr
tnc
teverse ot the tring
FrOgram 4:
Output
putEnter the input atringE)
= DVPythonProgramspythont
Enter the input
for i in rangelen(s)-1.-1-1 string abo
Reverse string= cba
printReverse strinE-)

Program 5: Write a Python program to check whether the input string is a palindrome n

s=input("Enter the input string


"
or n rangettenisP119
Output:
if(s-=r DPython Programs>python
printi'input string is a palindrome) Enter the input string aba
alse: Input string is a paindrom
printinput string iS not a palindrome)

Program 6: Write a Python program to find the frequency of characters occurring in as

the input string )


inputEnter
dumset)
in s:
or
1 not in o

uappeno
du.addi)
for i in ranget0,len(u)
tul

for jin range(0,lent6) Output


if(tsl:
Vave DPythonProgramsoj
res.appondy tnter
the input strin
printtinput string= "s) Input stringe a b a b
printFrequenoy ocOurronoe res) quency Occurrencan i
Strings and Regular Expressions 245

rogrom 7 W e a y n o n proz to nna tthe umber of vowels in an ingput string

In yon

inputt Enter the input strinE

o-0
Output
o
nProranpython 020Y
in ['a
cO+1 Ron
Enter theinct n
n a c o u n t of vowels: 2
ornttihe count of vowels:"o)

aram 8: Wrlte a l'ython proEram to find the number of consonants in the Inpur stine

ce0
Output
to

tin ['a'e¥,0ut DVythonProgrutis>python b2.py


CC+1 Entor the nput strinE mo &

The oount of
print"The count of consonant e) consonarnta
Program 9 WIe a y n o n PEOBrm to Thd the number of digits in tne uiput tE

uteEnter the input strnE9


0 Output
tor in
if sdigto PythonPrograms>python nePy
Enter the input string alb2o3A5
s
c o u n t or dieit charictors:
rintt"The 0ount of digit charactorsc)

Program 20 wnte aTython program to ftnd the number of whitespaces in the input strinE

Output
n p u t Enter tho input string

DPythonfProgramsopython
nter the nput strinE ROod
b2 py
for i in a
if iisspaceu
The count of white 5pac
print The count of white space
characters: characte

Program 11: Write a Fython proBram to reverse a sentence

Output
sainpull"Enter the input string 9PythonPrograms>python b2 py
Enter the input string hello
hai
for
i in rangelen(s-1 good
Reverse
+s sentenog doo nah
pirintiHeverse SentencoaH
248 Python Programming
Ogrom 23: Write a Python program to remove the words ending with v o w e l s

put Enter tho string

p Output
ii
0-1] not in ['a, a,7o.u DPythonroEramsopython
Enter the
b2 py
tnaapla is toodt

Program 24: Write a Python program to remove the words endng with consonants

xuinputrEnter the string")

Output
tor 1in y

alent0-11in f'a:e,7,o,u DVPythonOgr nb2oy


00dra
printi apple

Program 25:Wrile Python program to find the index of second string in


a
the first string
Output
x=input'Enter the string)
yinput Enter the string to be searohed: DEVythanroBramapython
Enter the
bapy
andexy) string abca
ftz-1 Th te
Printthe string2 is found in stringl at z, "index')
tringl at 1inca

Glossary
The string object uses ordinary string value.
Kaw
strings can be handled with regular expression.
Kegular expressions are used to handle text patterns efticlently.

Summary
*lhe string is used to represent character data.

Lach character of the string is accessed with the


corresponding index
value
The string can be iterated. Varlous operafions can be performed on the
string object
The string module provides various functions for handling strings in
Pytho0
Other than ordinary strlngs, raw strings can be efficiently handled by the
The Re module is used for pertorming various operations with the
regular expcess
regular expressios

You might also like