CHAPTER 8
STRINGS AND
STRING
MANIPULATIO
• Know how to process text.
• Understanding various string
functions in Python.
• Know how to format Strings.
• Know about String Slicing.
• Know about Strings
application in real world.
Introduction
• String is a data type in
python, which is used
to handle array of
characters.
• String is a sequence of
Unicode characters that
may be a combination
EXAMPLE
print('Welcome to
learning Python' )
print("Welcome to
learning Python")
print("""Welcome to
A string in Python can
be created using single
or double or even triple
quotes.
String in single quotes
cannot hold any other
single quoted character
To overcome this
problem, you have to
use double quotes.
Strings which contains
double quotes should
be define within triple
quotes.
Defining strings within
EXAMPLE
print (‘Greater
Chennai Corporation’)
Greater Chennai
Corporation
EXAMPLE
print (“Computer
Science”)
Computer
Science
EXAMPLE
print (''' "Computer
Science" ''')
"Computer
Science"
EXAMPLE
print (''' "Strings are
immutable in 'Python',
which means you can't
make any changes
once you declared" ''')
"Strings are immutable in
'Python',
Accessing
characters in
a String
Once you define a string,
python allocate an index
value for its each
character.
These index values are
otherwise called as
subscript which are used to
• The positive
subscript 0 is
assigned to the first
character and n-1 to
the last character,
where n is the
number of characters
in the string.
EXAMPLE
EXAMPLE
str1 = input ("Enter a
string: ")
index=0
for i in str1:
print
("Subscript[",index,"] :
OUTPUT
Enter a string: HELLO
Subscript[ 0 ] : H
Subscript[ 1 ] : E
Subscript[ 2 ] : L
Subscript[ 3 ] : L
Subscript[ 4 ] : O
EXAMPLE
str1 = input ("Enter a string: ")
index=-1
while index >= -(len(str1)):
print ("Subscript[",index,"] : " +
str1[index])
index += -1
output
Subscript[ -1 ] : O
Subscript[ -2 ] : L
Subscript[ -3 ] : L
Subscript[ -4 ] : E
General formate
of
replace function:
replace(“char1”,
“char2”)
EXAMPLE
str1="How are you"
print (str1)
print
([Link]("o",
"e"))
output
How are you
EXAMPLE
>>> str1="How are you"
>>> del str1[2]
output
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
del str1[2]
TypeError: 'str' object doesn't support item
deletion
String
Operators
Python provides
the following
operators for
string
operations.
These operators
1. Concatenation
Joining (+)
of two or
more strings is
called as
Concatenation.
EXAMPLE
str1 = "Hello"
str2 = "World"
print(str1 + str2)
Output
Hello World
2. Append (+
at the=)
• Adding more strings
end of an
existing string is
known as append.
• The operator += is
EXAMPLE
fruits = ["apple",
"banana", "cherry"]
#[Link]("orang
e")
fruits+= ["orange"]
[Link]
The (*)
multiplication
operator (*) is
EXAMPL
E
>>>str1="Welcome "
>>> print (str1*4)
Welcome Welcome
Welcome Welcome
4 String slicing
Slice is a substring of a main
string.
A substring can be taken from
the original string by using [ ]
operator and index or subscript
values.
General format of slice
operation:
str[start:end]
Where start is the
beginning index
and end is the last
index value of a
character in the
string.
Python takes the
If you want to slice first 4
characters from a string,
you have to specify it as 0
to 5.
Because, python consider
only0 the
1 2end
3 4value
5 6 7as8n-1.
9 1
0
TH I RUKURRA L
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
EXAMPLE 1
slice a single character
from a string
>>>str1="THIRUKKURA
L"
>>> print (str1[0])
T
EXAMPLE 2
slice a substring from
index 0 to 4
str="THIRUKKURAL"
print(str[0:4])
Output
EXAMPLE 3
slice a substring using
index 0 to 4 but without
specifying the beginning
index.
>>> print (str1[:5])
THIRU
EXAMPLE 3
slice a substring
using index 0 to 4 but
without specifying
>>> print (str1[6:])
the end
KURAL index
Example V : Program to slice substrings using
forstr1="COMPUTER"
loop
index=0
for i in str1:
print (str1[:index+1])
index+=1
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
[Link] when slicing string
When the slicing operation,
you can specify a third
argument as the stride, which
refers to the number of
characters to move forward
after the first character is
retrieved from the string.
The default value of stride is
1.
EXAMPLE
>>> str1 = "Welcome to learn
Python"
>>> print (str1[10:16])
learn
>>>print(str1[Link])
r
>>> print (str1[Link])
er
>>> print (str1[::3])
Note: Remember that, python takes the last
value as n-1 You can also use negative value as
stride (third argument). If you specify a
negative value, it prints in reverse order.
>>> str1 = "Welcome to learn
Python"
>>> print(str1[::-2])
nhy re teolW
String Formatting Operators
The formatting
operator % is used
to construct
strings, replacing
parts of the
SYNTAX
(“String to be display with %val1 and
%val2” %(val1, val2))
EXAMPLE
name = "Rajarajan"
mark = 98
print ("Name: %s and
Marks: %d" %
(name,mark))
Output Name: Rajarajan
Formatting characters
Escape sequence in
Escape
python sequences starts
with a backslash(\) and it
can be interpreted
differently.
When you have use
single quote to represent
a string, all the single
quotes inside the string
EXAMPLE
print ('''They said,
"What's there?"''')
output
They said,
"What's there?"
The format( )
function
EXAMPL
E
print ("Hello, I am {} years
old !".format(18))
output
Hello, I am 18
years old !
EXAMPLE
print ("This is {} {} {} {}"
.format("one", "two",
"three", "four"))
output
This is one two
three four
EXAMPLE
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of {} and {} is
{}".format(num1, num2,
(num1+num2)))
output
Number 1: 3
Number 2: 4
The sum of 3 and 4 is 7
Built-in String
functions
len
syntax
len(str)
EXAMPLE
A="Corporation"
print(len(A))
output
11
capitalize
syntax
capitalize( )
Used to capitalize
the first character of
the string
EXAMPLE
A="chennai"
print([Link](
))
output
Chennai
center
synta
center(width, fillchar)
xReturns a string with the
original string centered to a
total of width columns and
filled with fillchar in columns
that do not have characters
EXAMPL
A="chennai"
E
print([Link](1
5,'*'))
output
****chennai*
find
syntax
find(sub[, start[, end]])
The function is used to
search the first occurrence of
the sub string in the given
string. It returns the index at
which the substring starts.
It returns -1 if the substring
does not occur in the string.
•sub - It's the
substring to be
searched in
the str string.
•start and end (optio
nal) - substring is
>>>str1=’mammals’
>>>[Link](‘ma’)
0
On omitting the start parameters,the
function starts the searchfrom the
beginning.
>>>[Link](‘ma’,2)
3
>>>[Link](‘ma’,2,4)
-1
Displays -1 because the substring could not
be found between the index 2 and 4-1.
>>>[Link](‘ma’,2,5)
3
isalnum
syntax
Isalnum()
The isalnum() returns:
True if all characters in the
string are alphanumeric
False if at least one
character is not
alphanumericReturns True
if the string contains only
letters and digit. It returns
EXAMPLE
name =
“E234xcel"
print([Link]
output
m())
True
EXAMPL
E
name =
“E234xcel@"
print([Link]
output
m())
False
isalpha
syntax
isalpha( )
True if all
characters in the
string are
alphabets (can
be both
lowercase and
EXAMPL
E
name = "excel"
print([Link]
output
a())
True
EXAMPLE
name = "excel1"
print([Link]
output
a())
False
isdigit
syntax
isdigit( )
True if all characters
in the string are
digits.
False if at least one
character is not a
digit. Returns True if
EXAMPLE
name = “12345"
print([Link](
output
))
True
EXAMPLE
name = “a12345"
print([Link](
output
))
False
lower
syntax
lower( )
Returns the exact
copy of the string with
all the letters in
lowercase.
EXAMPLE
str1='SAVE EARTH'
print([Link]())
output
save earth
islower
syntax
islower( )
EXAMPL
E
str1='excel'
print([Link](
))
output
True
EXAMPL
E
str1=‘Excel'
print([Link](
))
output
False
isupper
syntax
isupper( )
Returns
True if the
string is in
EXAMPL
E
str1='EXCEL'
print([Link](
))
output
True
EXAMPL
E
str1='Excel'
print([Link](
))
output
False
upper
syntax
upper( )
Returns the
exact copy
of the string
with all the
EXAMPL
E
str1='save earth'
print([Link]())
output
SAVE EARTH
title
syntax
title( )
Returns a string
in title case The
title() method returns
a string with first
letter of each word
capitalized; a title
EXAMPL
E
str1='education
department'
print([Link]())
output
Education
title() with apostrophes
EXAMPL
E text = "He's an
engineer, isn't he?"
print([Link]())
output
He'S An
swapcas
syntaxe
swapcase( )
It will change case of
every character to its
opposite case vice-
versa. The string
swapcase() method
converts all uppercase
characters to
EXAMPL
E
text = "He's An
EnGiNeer, IsN't He?"
print([Link]())
output
hE'S aN eNgInEER,
count
syntax
count( )
The string
count() method
returns the
number of
occurrences of
Returns the number
of substrings occurs
within the given
range. Remember
that substring may
be a single character.
Range (beg and end)
substring - string
whose count is to be
found.
beg(Optional) -
starting index within
the string where
search starts.
EXAMPL
string = "Python is
E
awesome, isn't it?"
substring = "is"
count =
[Link](substring)
output
print("The count is:",
count)
The count is: 2
EXAMPL
str1 = "Raja Raja Chozhan"
E
print([Link]('Raja'))
2
print([Link]('r'))
0
print([Link]('R'))
2
print([Link]('a'))
5
print([Link]('a',0,5))
2
print([Link]('a',11))
1
ord
syntax
ord(char )
Returns the
ASCII code of
EXAMPL
E
ch = 'A'
print(ord(ch))
print(ord('B'))
output
65 66
chr
syntax
chr(ASCII )
Returns the
character
represented by
EXAMPL
ch = 97
E
print(chr(ch
))
print(chr(10
output
0))
ad
Membershi
p Operators
The ‘in’ and ‘not in’
operators can be
used with strings
to determine
whether a string is
present in another
string.
Evaluates to true
if it finds a
variable in the
in
specified sequence
and false
otherwise
Evaluates to true
EXAMPL
list1=[1,2,3,4,5]
E
if 5 in list1:
print("Yes",list1)
else:
print("No",list1)
Yes [1, 2, 3, 4, 5]
EXAMPL
list1=[1,2,3,4,5]
E
if 10 in list1:
print("Yes",list1)
else:
print("No",list1)
No [1, 2, 3, 4, 5]
EXAMPL
E
list2=['h','e','l','l','o']
if 'e' in list2:
print("Yes",list2)
else:
print("No",list2)
Yes ['h', 'e', 'l', 'l',
EXAMPL
E
list2=['h','e','l','l','o']
if ‘g' in list2:
print("Yes",list2)
else:
print("No",list2)
No ['h', 'e', 'l', 'l',
EXAMPL
E
list2=['h','e','l','l','o']
if ‘g' not in list2:
print("Yes",list2)
else:
print("No",list2)
Yes ['h', 'e', 'l', 'l',
EXAMPL
E
list2=['h','e','l','l','o']
if ‘e' not in list2:
print("Yes",list2)
else:
print("No",list2)
No ['h', 'e', 'l', 'l',
EXAMPL
a = 10
E
b = 20
list = [1, 2, 3, 4, 5, 20];
if b in list :
print ("Line 1 - a is available in
the given list")
else:
print ("Line 1 - a is not available
Line 1 - a is
in the given list")
available in the
EXAMPL
a = 10
E
b = 20
list = [1, 2, 3, 4, 5, 20,10];
if a not in list :
print ("Line 1 - a is available in
the given list")
else:
print ("Line 1 - a is not available
Line 1 - a is
in the given list")
not available
EXAMPL
str1=input
E ("Enter a
string: ")
str2="chennai"
if str2 in str1:
print ("Found")
else:
def rem_vowels(s):
temp_str=''
for i in s:
if i in "aAeEiIoOuU":
pass
else:
temp_str+=i
print ("The string without
vowels: ", temp_str)
str1= input ("Enter a String: ")
rem_vowels (str1)
ILAVARASAN
, MCA,
MHRM, MEd
Hands on
Experienc
Write a python program to find
the length of a string.
str = input ("Enter a
string")
print (len(str))
Write a program to count the
occurrences of each word in a
given string.
Write a program to add a
prefix text to all the lines in a
string.