Strings - 1
Strings - 1
12
Expressions
string object
in Python ne ord
the handling
of
at
strings
sn s
an be handled wingular expre
elaborates on
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
al0:2
lo
this strin
del(a[o)
TracebacK
Frlecstdin>, ne cmouue
tings and Regular Expressions 2
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
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
Kood morning
» lena,
12
below.
listed method.
are italize
methods
with capitalizeU
Varlous ring capitalized
'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
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
>> lenta)
b
254 Python Programming
OUtput
ORSTUVwz
the value of letters stant
abedelghjidmnopgrstuvwxyzABCDErGHRMO
The value of wi
vaam of printable constant:
ogheimnoparstuvwxyzABcDEFaHLDRLMRO wwA"Ne 0
Output
DVPyth
thonPrO
Entar the input strine
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
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
Output
h o n D2 p y
0Pytho ringthis is
very good and is happy
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
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
Output
DWyhoProuramspylnon bY
lnpad dth to tb afilled.
Enter the pur otE EO
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
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
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
Output
s(10.20.30,0,b0 DPYthonr python ta,
axis
PEtethe max rusultw
m u t e 50 2y
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
tifier0
Output
trine a dentitier)
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)
Output
DPythonPrograms>python al.pY
Enter intoger walun.
a=inttinputtEnter intoor value:
pneintegor value: Sd 96a) Integer value: 10
Output
DVythonPrograms>pyhon a.Py
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
for 1in
inot in du nornimk
0Vythtnrora pythe 2
lle
xjoinisorteds tring- ehlio rie
Printthe alphabetical order sorted stringe
Outpu
DVython Saay
23de
printThe string with alphabatse
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
af each
rom 19 to check whether the iput strings are anagranms
PrOg
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
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
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
Program 5: Write a Python program to check whether the input string is a palindrome n
uappeno
du.addi)
for i in ranget0,len(u)
tul
In yon
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
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
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
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
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
Output
tor 1in y
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.