06 String Manipulation 2023-24

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Chapter – 6 XI CS & IP

String Manipulation
String: A String is a sequence of characters. In Python string literals are sequence of characters
enclosed in either single or double quotes. eg.

“Hello world” , “123450” , ‘Exam 2018-19’

There are two String types in Python:


i.) Single-line Strings: The strings enclosed in single or double quotes, which
terminate in one line are Single-line strings.
Eg: “Learning is Fun”

ii.) Multiline Strings: The strings which are written in two or more lines are
called as multiline strings. In Python multiline strings can be created in two
ways:-
a. By adding a back-slash at the end of string and then press Enter key to
continue typing text in the next line.
Example:

str1 = “This is demo\


of Multiline\
String”

After the above statements if you print the value of str1, you will get:

“This is demo of Multiline String”

b. By typing the text in triple quotation marks, either single or double


quotation marks.
Example:
str1 = “ “ “ This is demo
of Multiline
String ” ” ”

After the above statements if you print the value of str1 you will get:

“This is demo\nof Multiline\nString”

Notice the \n(newline character) is also added to the string. The symbol
‘\n’ will be displayed when this code is tried in Interactive mode.

1
Traversing a String:

Traversing refers to iterating through the elements of a String one character at a


time. Individual characters of a String are accessible through the unique index
number of each character. The index numbers in a string are assigned as follows:

If a string Name is created in the following way:


Name = “PYTHON”

Then it is stored in the memory as:

Forward Indexing
Index Numbers 0 1 2 3 4 5
Name P Y T H O N
Index Numbers -6 -5 -4 -3 -2 -1
Backward Indexing

Individual items can be accessed from the String using the Index numbers, for example if you
want to access alphabet ‘T’ then you can write the following print statements:

print(Name[2]) or print(Name[-4])

 If you want to print the complete string then write:

print(Name)

 If you will try to write the following statement:

print(Name[6])

It will show Error message that “String Index out of range”

 If you will try the following statement to modify a character:

Name[2] = ‘K’

It will show an Error message that “str object does not support item assignment”
because the Strings are immutable.

2
STRING OPERATORS:
1. Basic Operators: The two basic operators of strings are:

a. Concatenation Operator (+): This operator is used to join 2 strings. The few
examples of use of Concatenation operator are as follows:

Input “Hello” + “World”


Output ‘HelloWorld”

Input “50” + “100”


Output ‘50100’

Input 50 + 100
Output 150

Input “Hello” + 25
Output Error, because String cannot be joined
with numeric value

b. Replication Operator (*): This operator is used to repeat a string. The few examples
of use of Replication operator are as follows:

Input “Hello” * 3
Output ‘HelloHelloHello”

Input 5 * “37”
Output ‘373737’

Input 4 * 60
Output 240

Input “Hello” * “5”


Output Error, because both operands cannot be
of String type

3
2. Membership Operators: The two membership operators are in / not in. These are used
to check whether a particular character or substring appears in a string or not. Both the
operands in Membership Operators should be of string type.
Example:

Input “a” in “India”


Output True

Input “eat” in “Great”


Output True

Input “put” not in “Computer”


Output False

3. Comparison Operators: All the comparison operators i.e. all Relational Operators (<,
<=, >, >=, = =, !=) apply to strings also. The comparisons using these operators are based
on the standard character-by-character comparison rules for Unicode (i.e. in dictionary
order).
Equality and Non-equality in strings are easier to determine because it goes for
exact character matching for individual letters including the case (upper case or lower
case) of the letter.
Example:

Input “A” = = “A”


Output True

Input “Weak” != “Week”


Output True

Input “C” = = “Cat”


Output False

For other comparisons like greater than ( > ) or less than ( < ) Python compares using
Unicode values (also called Ordinal value). Each character in memory is assigned a
unique integer value, called as Ordinal value, through which the character is identified.
The most common characters and their ordinal values are:

Character Ordinal Value


‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
0 to 9 48 to 57
Thus uppercase alphabets are considered as smaller than lowercase alphabets.
4
Example:

Input “a” < “A”


Output False

Input “ABC” > “AB”


Output True

Input “abc” < = “ABC”


Output False

The ord( ) function:


Python offers a built in function ord( ) that takes a single character and returns the
corresponding ordinal value (Unicode value) of it. It is used as per the following sntax:

ord(single_character)

For example, to know the ordinal value of alphabet a write it in the following way:

Input Ord(“A”)
Output 65

Note: The ord( ) function requires single character only. You may even write an escape
sequence enclosed in single quotes for ord( ) function.

The chr( ) function:


The chr( ) function does just opposite of ord( ) function. The chr( ) function takes
an integer value (ordinal value) and returns its corresponding character. It is used as per
the following syntax:

chr( integer_value)

Example:
Input chr(70)
Output F

5
STRING SLICES
String Slice refers to the part of a string. Strings are sliced using a range of indices. The
syntax for slicing a string is:

strname[n : m]

here strname is name of string variable, n is starting index and m is ending index
number. It will return all the characters between n and m-1.

Sample String:

str1 = “Programming”
0 1 2 3 4 5 6 7 8 9 10
P r o g r a m m i n g
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Some examples of string slices are:

Input str1[ 0 : 7 ] Slicing a string using Forward Indexes


Output ‘Program’

Input str1[ -8 : -4 ] Slicing a string using Backward Indexes


Output ‘gram’

Skipping Starting index value, missing


Input str1[ : 4 ]
index will be taken as 0 (zero)
Output ‘Prog’

Skipping Ending index value, missing


Input str1[ 7 : ]
index will be taken as 11.
Output ‘ming’

6
Slicing using combination of forward and backward indexing.

Index number 10 appears on right hand


Input str1[ -6 : 10 ] side of the index -6, so characters from -6
to 9 will be displayed as output.
Output ‘ammin’
Index number 1 appears on left hand side
Input str1[ -5 : 1 ] of the index -5, so it will return an empty
string.
Output ‘’
Index number 1 appears on left hand side
of the index -5 and step is given as -1, so
Input str1[ -5 : 1 : -1 ]
it will extract the characters in reverse
order from index no. -5 to index no. 2.
Output ‘margo’

Using step in Slicing the string:


You can give a third index i.e. step in a string slice too, which works as increment to
access the characters from string.
Example:
Input str1[ 1 : 11 : 2 ]
Increment of 2 is given to access the
Output ‘rgamn’ characters, so only characters at index
numbers 1, 3, 5, 7, 9 are displayed.

Out of bound (range) index numbers in Slicing:


If index number is out of bound (range) it doesn’t give error. It results into either the
characters fall in the bounds or an empty string.

Example:

Input str1[ 4 : 25 ]
Characters at index numbers 4 to 10 are
displayed. It will not display anything for
Output ‘ramming’
index numbers 11 to 25 as these index
numbers are out of bound.

Input str1[ 15 : 25 ]
The output is Empty String, as both the
Output ‘’
index numbers are out of bound.

7
Slicing String in Reverse Order:
To slice the string in reverse order we need to write the starting and ending index
numbers in reverse order and the third index as negative value.

Example:

Input str1[ : : -1 ]
Output ‘gnimmargorP’ The complete string is reversed.

Input str1[ 8 : 2 : -1 ]
String starting from index no. 8 to index
Output ‘immarg’
no. 3, in reverse order.

Input str1[ 10 : 0 : -2 ]
Alternate values starting from index no.
Output ‘gimro’ 10 to index no. 1 in reverse order are
displayed.

8
STRING FUNCTIONS AND METHODS
Python offers many built-in functions and methods for string manipulation. Every
string object created in Python is actually an instance of string class. The different string
functions can be applied to string as per the following syntax:
stringObject.methodName( )
StringObject can either be a string literal or a string variable that holds a string value.

The different string functions are:

1. string.capitalize( ): This function returns the string with first letter capitalized. If
the string is in upper case then first letter will remain capitalized and all other
characters convert into lower case.
Example:

name = “ayush sharma”


Input
name.capitalize( )
Output ‘Ayush sharma’ Only first letter is capitalized.

Input name = “AYUSH SHARMA”


First letter is capitalized and
Output ‘Ayush sharma’ other alphabets are converted
into lower case.

subject1 = “english"
Input subject 2 = subject1.capitalize( )
subject1
Output ‘english’ String in subject1 remains same.
Input subject2
subject2 contains the string with
Output ‘English’
first letter capitalized.

2. string.lower( ): This function returns a copy of the string converted to lowercase.


It doesn’t change the original string, it only coverts and displays the string in
lowercase.
Note: The string may contain numerics, symbols and spaces also.
Example:
regno = “RJ 38 CA 1234”
Input
regno.lower( )
All uppercase alphabets converted
Output ‘rj 38 ca 1234’ into lowercase. Digits, spaces and
symbols are allowed.

9
3. string.upper( ): This function returns a copy of the string converted to uppercase.
It doesn’t change the original string, it only coverts and displays the string in
uppercase.
Note: The string may contain numerics, symbols and spaces also.

Example:

email = “[email protected]
Input
email.upper( )
All lowercase alphabets
Output ‘[email protected]’ converted into uppercase. Digits,
spaces and symbols are allowed.

subject = “Informatics Practices”


Input
subject.upper( )
Output ‘INFORMATICS PRACTICES’

4. string.title( ): This function returns a copy of the string converted to titlecase i.e.
first letter of each word is capitalized in the string. It doesn’t change the original
string, it only coverts and displays the string in title case.
Note: The string may contain numerics, symbols and spaces also.

Example:
regno = “rj 38 ca 1234”
Input
regno.title( )
First letter of each word is
Output ‘Rj 38 Ca 1234’ capitalized. Digits, spaces and
symbols are allowed.

movie = “THE LOST WORLD”


Input
movie.title( )
First letter of each word is
Output ‘The Lost World’
capitalized.

5. string.islower( ): This function returns True if all the alphabets in the string are
lower case alphabets and there is at least one character, False otherwise.

Note: The string may contain numerics, symbols and spaces also.

10
Example:

email = “[email protected]
Input
email.islower( )
All alphabets are in lower case,
Output True digits, spaces and symbols are
allowed.

subject = “Informatics Practices”


Input
subject.lower( )
String contains upper case
Output False
alphabets also.

6. string.isupper( ): This function returns True if all the alphabets in the string are
upper case alphabets and there is at least one character, False otherwise.
Note: The string may contain numerics, symbols and spaces also.

Example:
regno = “RJ 38 CA 1234”
Input
regno.isalpha( )
All alphabets are in upper case,
Output True digits, spaces and symbols are
allowed.

7. string.istitle( ): This function returns True if first letter of all the words in the
string is an upper case alphabet and there is at least one character, False
otherwise.

Note: The string may contain numerics, symbols and spaces also.

Example:

model = “Redmi Note 9 Pro”


Input
model.istitle( )
First letter of each word in the
Output True
string is in upper case.

movie = “Fast and Furious”


Input
movie.istitle( )
First letter of word ‘and’ is
Output False
lowercase alphabet.

11
8. string.isalnum( ): This function returns True if all the characters in the string are
either all alphabets, all numerics or both and there is at least one character,
otherwise False.

Note: If any space or special symbol is used in string then it returns False.

Example:

name = “Ayush”
Input
name.isalnum( )
All characters in string are
Output True
alphabets.

model = “narzo10”
Input
model.isalnum( )
All characters in string are
Output True
alphabets and digits.

regno = “RJ 38 CA 1234”


Input
regno.isalnum( )
Output False Spaces are used in string.

9. string.isalpha( ): This function returns True if all the characters in the string are
alphabets and there is at least one character, False otherwise.

Note: If any digit, space or special symbol is used in string then it returns False.

Example:

name = “Ayush”
Input
name.isalpha( )
All characters in string are
Output True
alphabets.

regno = “RJ 38 CA 1234”


Input
regno.isalpha( )
Digits and Spaces are used in
Output False
string.

12
10. string.isdigit( ): This function returns True if all the characters in the string are
digits and there is at least one character, False otherwise.
Note: If any alphabet, space or special symbol is used in string then it returns
False.

Example:

session = “2020-21”
Input
session.isdigit( )
String must not contain any
Output False
special symbol.

rollno = “11251”
Input
rollno.isdigit( )
All characters in string are
Output True
digits.

11. string.isspace( ): This function returns True if all the characters in the string are
whitespaces and there is at least one character, otherwise it returns False.

Note: If any alphabet, digit or special symbol is given in string then it returns
False.

Example:

name = “”
Input
name.isspace( )
At least one space is required,
Output False
given string is an Empty string.

subject = “ ”
Input
subject.isspace( )
All characters in string are
Output True
spaces only.

12. string.find( ): This function finds a substring in a string and returns the index
number of its first occurrence.
You can specify Start and End as starting and ending index numbers
where you want to look for the substring.
This function returns –1 if substring is not found.

13
Example:

animals = “Cat Rat and Bat”


Input
animals.find( “at” )
Index number of first occurrence
Output 1
of ‘at’ in string is returned.

Input animals.find( “at” , 6 , 15 )


Index number of first occurrence
Output 13 of ‘at’ starting from index
number 6, is returned.

Input animals.find( “ca” )


Returns -1as ‘ca’ doesn’t appear
Output -1
in the string.

13. string.index( ): This function is similar to find function. It checks for a substring
in a string and returns the index number of its first occurrence.
You can specify Start and End as starting and ending index numbers
where you want to look for the substring.
This function displays Error message if substring is not found.

Example:

animals = “Cat Rat and Bat”


Input
animals.index( “at” )
Index number of first occurrence
Output 1
of ‘at’ in string is returned.

Input animals.index( “at” , 6 , 15 )


Index number of first occurrence
Output 13 of ‘at’ starting from index
number 6, is returned.

Input animals.index( “ca” )


Displays error message as ‘ca’
Output Value Error: Substring not found.
doesn’t appear in the string.

14
14. string.count( ): This function counts and returns the number of occurrences of a
substring in a string.

Example:

animals = “Cat Rat and Bat”


Input
animals.count( “at” )
Substring ‘at’ appears 3 times in
Output 3
the string.

15. string.startswith( ): This function returns True if the string starts with the given
substring, otherwise returns False.

Example:

subject = “Computer Science”


Input
subject.startswith( “Comp” )
Output True The string starts with “Comp”

16. string.endswith( ): This function returns True if the string ends with the given
substring, otherwise returns False.

Example:

subject = “Computer Science”


Input
subject.endswith( “Comp” )
The string doesn’t ends with
Output False
“Comp”

17. string.replace( ): This function replaces a substring in the string with the given
substring.

Example:

animals = “Cat Rat and Bat”


Input
animals.replace( “at”, “oat” )
All the occurrences or ‘at’ in
Output ‘Coat Roat and Boat’
string are replaced with ‘oat’.

15
18. string.strip( ): This function returns copy of the string after removing the
specified characters from the beginning and end of the string. It removes the
specified characters from the left and right of the string. The specified characters
may appear in any order but in string to remove the specified characters, those
must be in continuation. To the left and right of the string one or more specified
characters may appear in any order.
Note: If strip( ) is used without any argument, it removes the leading and trailing
whitespaces.

Example:

movie = “fast and furious”


Input
movie.strip(“sufa” )
From left side ‘fas’ is removed
Output ‘t and furio’ and from right side ‘us’ is
removed.

19. string.lstrip( ): This function returns copy of the string after removing the
specified characters from the beginning of the string. It removes the specified
characters from the left of the string. The specified characters may appear in any
order but in string to remove the specified characters, those must be in
continuation. To the left of the string one or more specified characters may
appear.
Note: If lstrip( ) is used without any argument, it removes the leading
whitespaces.
Example:

movie = “fast and furious”


Input
movie.lstrip(“sufa” )
Output ‘t and furious’ From left side ‘fas’ is removed.

20. string.rstrip( ): This function returns copy of the string after removing the
specified characters from the end of the string. It removes the specified characters
from the right of the string. The specified characters may appear in any order but
in string to remove the specified characters, those must be in continuation. To the
ritht of the string one or more specified characters may appear.

Note: If rstrip( ) is used without any argument, it removes the trailing


whitespaces.

16
Example:
movie = “fast and furious”
Input
movie.rstrip(“sufa” )
Output ‘fast and furio’ From right side ‘us’ is removed.

21. string.split( ): This function splits (divides) a string in multiple parts from the
given substring or character. The substring which is used to split the string into
parts is not displayed in the output. The split strings are shown in a list form.

Example:

name = “Kartik aryan”


Input
name.split( “ar”)
The string is divided into
multiple parts from the substring
Output [‘K’ , ‘tik ’ , ‘yan’]
‘ar’ and the substring ‘ar’ is not
displayed in the result.

22. string.partition( ): This function partitions a string in two parts from the given
substring. It returns 3 strings as result: First string contains characters to the left of
given substring, Second string is the given substring itself and the Third string
contains the characters to the right of the given substring.
Example:

movie = “Fast and Furious”


Input
movie.partition( “and”)
The string is divided into two
Output (‘Fast ’ , ‘and’ , ‘ Furious’)
parts from the word ‘and’.

23. string.join( ): This function joins a string or character after each character of the
string or each element of the list (except the last character of the string).
Example:

name = “Kartik”
Input
“**”.join( name )
After each character of name the
Output ‘K**a**r**t**i**k’
substring ‘**’ is added.

cartoon = [“Tom”,“and”,“Jerry”]
Input
“@@@”.join( cartoon )
After each element of the list
Output ‘Tom@@@and@@@Jerry’
substring ‘@@@’ is added.
----- X -----

17

You might also like