INDIAN SCHOOL MUSCAT
CLASS XI
COMPUTER SCIENCE (083)
Chapter : String Manipulation
STRING MANIPULATION
Introduction
Traversing a String
String Operators
•Basic operators
•Membership operators
•Comparison operators
String Slices
String Functions and Methods
TRAVERSING A STRING
• It means accessing the individual characters of
string i.e. from first character to last character.
• OR Traversing refers to iterating through the
WRITE
elements of a string one character at a time.
• Every character in string is at different index
position i.e. from 0 to size-1
• For loop can be used to traverse the string very
easily. For .e.g
name="lovely"
for ch in name:
print(ch,'-',end='')
The above code will print
l -o -v -e -l -y -
STRING OPERATORS
WRITE
Two basic operators + and * are allowed
+ is used for concatenation (joining)
* Is used for replication (repetition)
String Concatenation Operator
WRITE
A="Computer"
B="Science"
C=A+B
print(C)
Output:
ComputerScience
String Concatenation Operator
PROGRAM OUTPUT:
WRITE
print('1'+'1') 11
print("a"+"0") a0
print("123"+"abc") 123abc
print(9+9) 18
print('9'+'9') 99
>>> '2'+3
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
'2'+3
TypeError: Can't convert 'int' object to str implicitly
String Replication Opearator
WRITE The * operator when used with numbers it
performs multiplication
To use * operator with strings, you need two
types of operands – string with a number.
For replication operator *, Python creates a new
string that is a number of repetitions of the input
string.
Line=“ go!”
print(Line*3)
String Replication Opearator
PROGRAM OUTPUT:
WRITE Line="go!" go!go!go!
print(Line*3) abcabc
print("abc"*2) @@@@@
print(5*"@") 1111111111
print("1"*10) :-:-:-:-
print(":-"*4)
>>> "2"*"3"
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
"2"*"3"
TypeError: can't multiply sequence by non-int of type 'str'
MEMBERSHIP OPERATORS
WRITE • Membership operators (in and not in) are used
to check the presence of character(s) in any
string.
• in- Returns True if a character or a substring
exists in the given string; False otherwise.
not in- Returns True if a character or a substring
does not exist in the given string;
False otherwise.
MEMBERSHIP OPERATORS
Example Output
WRITE "a" in "python" False
"a" in "Java" True
"per" in "operators" True
"men" in "membership" False
"Man" in "manipulation" False
"Pre" not in "presence" True
>>> sub="help"
>>> string="helping hand" True
>>> sub in string
COMPARISON OPERATORS
• We can apply comparison operators
(==, !=,>,<,>=,<=) on string.
• Comparison will be character by character.
>>> str1="program"
WRITE
Comparison of string will be
>>> str2="python"
based on The ASCII code
>>> str3="Python" of the characters.
Characters Ordinal/
Example Output
ASCII code
>>> str1==str2 False A-Z 65-90
>>> str1!=str2 True a-z 97-122
>>> str2=="python" True
0-9 48-57
>>> str2>str3 True
>>> str3<str1 True
STRING SLICING
As we know slice means “part of ”, so slicing is a
process of extracting part of string. Part of a
WRITE
string containing some contiguous characters from
the string. In previous chapters we already
discussed that string characters have their unique
index position from 0 to length-1 and -1 to
–length(backward)
Forward indexing 0 1 2 3 4 5 6
message W E L C O M E
-7 -6 -5 -4 -3 -2 -1 Backward indexing
0 1 2 3 4 5 6 7 8
Forward indexing wo n d e r f u l Backward indexing
-9 -8 -7 -6 -5 -4 -3 -2 -1
>>> str1="wonderful" >>> str1[3:3]
>>> str1[0:6] ''
'wonder' >>> str1[3:4]
WRITE
>>> str1[0:3] 'd'
'won' >>> str1[-5:-2]
>>> str1[3:6] 'erf'
'der' >>> str1[:-2]
>>> str1[-1:-3] 'wonderf'
'' >>> str1[:4] Reverse
>>> str1[-3:-1] 'wond' of string
'fu' >>> str1[-3:]
>>> str1[-3:0] 'ful'
'' >>>str1[::-1]
>>>str1[0::2] lufrednow
‘wnefl’
STRING FUNCTIONS AND METHODS
WRITE Python offers many built-in function for string
manipulation.
One method len( ) we have already used. Let us
understand other methods also.
To use string manipulation function the syntax
is:
String_Object.functionName()
STRING FUNCTIONS/METHODS
• len(string) :this function returns the number of
characters in any string including spaces.
WRITE
• [Link]() : Returns a copy of the string with its
first letter of sentence in capital letter.
• [Link]() : this function returns a copy of the
string converted to uppercase.
STRING FUNCTIONS/METHODS
• [Link]() : this function returns a copy of the string
WRITE converted to lowercase.
• [Link](substring,[start,[end]]) : this function
returns the lowest index position of substring in the given
string. We can also specify start and end index to modify
search criteria. It returns -1 if substring not found.
STRING FUNCTIONS/METHODS
WRITE • [Link]() : Returns True if the characters in the
string are alphanumeric(alphabets or numbers) and there is
at least one character, False otherwise.
STRING FUNCTIONS/METHODS
• string. islower(): this function returns True if all the
characters in string are lowercase there must be at least
WRITE one cased character, False otherwise.
• string. isupper() : this function returns True if all the
characters in string are uppercase there must be at
least one cased character, False otherwise. Both
islower() and isupper() will check the case only for
letter, if any symbol present in string it will be ignored.
STRING FUNCTIONS/METHODS
• [Link]() : Returns True if the string contains
only whitespace characters. There must be at least one
character. Returns False otherwise.
WRITE . [Link]() : it returns True if all the characters in
string are alphabets and there is at least one character,
False otherwise.
• [Link]() : it returns True if all the characters in
string are digits and there is at least one character, False
otherwise.
STRING FUNCTIONS/METHODS
• [Link]([chars]) : it returns a copy of string with leading
and trailing whitespaces removed. If chars is given, it remove
WRITE
characters instead.
• [Link]([chars]) : it returns a copy of string with leading
whitespaces removed. If chars is given, it remove characters
instead.
• [Link]([chars]) : it returns a copy of string with trailing
whitespaces removed. If chars is given, it remove characters
instead.
STRING FUNCTIONS/METHODS
• [Link](substring): this function returns index
position of substring. If substring is not there then it
WRITE returns error ‘substring not found’.
• [Link](): this function is used to convert first letter of
every word in string in capital letters.
STRING FUNCTIONS/METHODS
• count(substring, [start,[end]]) : this function is used to
find the number of occurrence of substring in our string.
WRITE We can give optional starting index from where searching
begin and also end index i.e. upto what index in string it will
search and count. It return 0 if substring not found.
• [Link](old,new) :this function replaces all the
occurrences of the old string with new string.
>>> str='hello'
>>> print([Link]('l','%'))
he%%o
>>> print([Link]('l','$$'))
he$$$$o
STRING FUNCTIONS/METHODS
• [Link](sep) : this function partitions the
WRITE strings at the first occurrence of separator, and returns
the string partition in three parts i.e. before the
separator, the separator itself and the part after the
separator. If the separator is not found, returns the
string itself followed by two empty strings.
>>> str='The Green Revolution'
>>> [Link]('Rev')
('The Green ', 'Rev', 'olution')
>>> [Link]('pe')
('The Green Revolution', '', '')
STRING FUNCTIONS/METHODS
• [Link]([sep[,maxsplit]]) : this function splits the
string into substrings using the separator. The second
WRITE argument is optional and its default value is zero. If an
integer value N is given for the second argument, the
string is split in N+1 strings.
>>> str="The$earth$is$what$we$all$have$in$common"
>>> [Link]('$',3)
['The', 'earth', 'is', 'what$we$all$have$in$common']
>>> [Link]('$')
['The', 'earth', 'is', 'what', 'we', 'all', 'have', 'in', 'common']
>>> str="The Green Revolution"
>>> [Link]('e')
['Th', ' Gr', '', 'n R', 'volution']
STRING FUNCTIONS/METHODS
WRITE The startswith() method returns True if a string starts with the
specified prefix(string). If not, it returns False.
Example
message = 'Python is fun'
# check if the message starts with Python
print([Link]('Python'))
# Output:
True
STRING FUNCTIONS/METHODS
The endswith() method returns True if a string ends with
WRITE
the specified suffix. If not, it returns False.
Example
message = 'Python is fun'
# check if the message ends with fun
print([Link]('fun'))
# Output:
True
STRING FUNCTIONS/METHODS
WRITE
The string join() method returns a string by
joining all the elements of an iterable (list, string,
tuple), separated by the given separator.
Example
text = ['Python', 'is', 'a', 'fun', 'programming', 'language']
# join elements of text with space
print(' '.join(text))
# Output:
Python is a fun programming language