Page 1
8.1 Introduct Ion We have studied in Chapter 5, that a sequence is an
orderly collection of items and each item is indexed by
an integer. Following sequence data types in Python
were also briefly introduced in Chapter 5.
• Strings
• Lists
• Tuples
Another data type ‘Dictionary’ was also introduced
in chapter 5 which falls under the category of mapping.
In this chapter, we will go through strings in detail.
List will be covered in Chapter 9 whereas tuple and
dictionary will be discussed in Chapter 10.
8.2 Str Ing S
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a letter,
digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single,
double or triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
str1, str2, str3, str4 are all string variables
having the same value 'Hello World!'. Values stored in
str3 and str4 can be extended to multiple lines using
triple codes as can be seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
“The great thing about a
computer notebook is that no
matter how much you stuff
into it, it doesn't get bigger or
heavier. ”
– Bill Gates
Chapter 8
Strings
In this chapter
» Introduction to
Strings
» String Operations
» Traversing a String
» Strings Methods
and Built-in
Functions
» Handling Strings
Ch 8.indd 175 08-Apr-19 12:39:21 PM
2024-25
Page 2
8.1 Introduct Ion We have studied in Chapter 5, that a sequence is an
orderly collection of items and each item is indexed by
an integer. Following sequence data types in Python
were also briefly introduced in Chapter 5.
• Strings
• Lists
• Tuples
Another data type ‘Dictionary’ was also introduced
in chapter 5 which falls under the category of mapping.
In this chapter, we will go through strings in detail.
List will be covered in Chapter 9 whereas tuple and
dictionary will be discussed in Chapter 10.
8.2 Str Ing S
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a letter,
digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single,
double or triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
str1, str2, str3, str4 are all string variables
having the same value 'Hello World!'. Values stored in
str3 and str4 can be extended to multiple lines using
triple codes as can be seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
“The great thing about a
computer notebook is that no
matter how much you stuff
into it, it doesn't get bigger or
heavier. ”
– Bill Gates
Chapter 8
Strings
In this chapter
» Introduction to
Strings
» String Operations
» Traversing a String
» Strings Methods
and Built-in
Functions
» Handling Strings
Ch 8.indd 175 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 176
8.2.1 Accessing Characters in a String
Each individual character in a string can be accessed
using a technique called indexing. The index specifies
the character to be accessed in the string and is written
in square brackets ([ ]). The index of the first character
(from left) in the string is 0 and the last character is n-1
where n is the length of the string. If we give index value
out of this range then we get an IndexError. The index
must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including
variables and operators but the expression must
evaluate to an integer.
#an expression resulting in an integer index
#so gives 6
th
character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers
Python allows an index value to be negative also.
Negative indices are used when we want to access the
characters of the string from right to left. Starting from
right hand side, the first character has the index as -1
and the last character has the index –n where n is the
length of the string. Table 8.1 shows the indexing of
characters in the string ‘Hello World!’ in both the cases,
i.e., positive and negative indices.
>>> str1[-1] #gives first character from right
'!'
>>> str1[-12]#gives last character from right
'H'
Python does not have
a character data type.
String of length one is
considered as character.
Ch 8.indd 176 08-Apr-19 12:39:21 PM
2024-25
Page 3
8.1 Introduct Ion We have studied in Chapter 5, that a sequence is an
orderly collection of items and each item is indexed by
an integer. Following sequence data types in Python
were also briefly introduced in Chapter 5.
• Strings
• Lists
• Tuples
Another data type ‘Dictionary’ was also introduced
in chapter 5 which falls under the category of mapping.
In this chapter, we will go through strings in detail.
List will be covered in Chapter 9 whereas tuple and
dictionary will be discussed in Chapter 10.
8.2 Str Ing S
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a letter,
digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single,
double or triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
str1, str2, str3, str4 are all string variables
having the same value 'Hello World!'. Values stored in
str3 and str4 can be extended to multiple lines using
triple codes as can be seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
“The great thing about a
computer notebook is that no
matter how much you stuff
into it, it doesn't get bigger or
heavier. ”
– Bill Gates
Chapter 8
Strings
In this chapter
» Introduction to
Strings
» String Operations
» Traversing a String
» Strings Methods
and Built-in
Functions
» Handling Strings
Ch 8.indd 175 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 176
8.2.1 Accessing Characters in a String
Each individual character in a string can be accessed
using a technique called indexing. The index specifies
the character to be accessed in the string and is written
in square brackets ([ ]). The index of the first character
(from left) in the string is 0 and the last character is n-1
where n is the length of the string. If we give index value
out of this range then we get an IndexError. The index
must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including
variables and operators but the expression must
evaluate to an integer.
#an expression resulting in an integer index
#so gives 6
th
character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers
Python allows an index value to be negative also.
Negative indices are used when we want to access the
characters of the string from right to left. Starting from
right hand side, the first character has the index as -1
and the last character has the index –n where n is the
length of the string. Table 8.1 shows the indexing of
characters in the string ‘Hello World!’ in both the cases,
i.e., positive and negative indices.
>>> str1[-1] #gives first character from right
'!'
>>> str1[-12]#gives last character from right
'H'
Python does not have
a character data type.
String of length one is
considered as character.
Ch 8.indd 176 08-Apr-19 12:39:21 PM
2024-25
String S 177
An inbuilt function len() in Python returns the length
of the string that is passed as parameter. For example,
the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'
8.2.2 String is Immutable
A string is an immutable data type. It means that
the contents of the string cannot be changed after it
has been created. An attempt to do this would lead to
an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment
8.3 Str Ing o perat Ion S
As we know that string is a sequence of characters.
Python allows certain operations on string data type,
such as concatenation, repetition, membership and
slicing. These operations are explained in the following
subsections with suitable examples.
8.3.1 Concatenation
To concatenate means to join. Python allows us to join
two strings using concatenation operator plus which is
denoted by symbol +.
Table 8.1 Indexing of characters in string 'Hello World!'
Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l l o W o r l d !
Negative Indices -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Ch 8.indd 177 08-Apr-19 12:39:21 PM
2024-25
Page 4
8.1 Introduct Ion We have studied in Chapter 5, that a sequence is an
orderly collection of items and each item is indexed by
an integer. Following sequence data types in Python
were also briefly introduced in Chapter 5.
• Strings
• Lists
• Tuples
Another data type ‘Dictionary’ was also introduced
in chapter 5 which falls under the category of mapping.
In this chapter, we will go through strings in detail.
List will be covered in Chapter 9 whereas tuple and
dictionary will be discussed in Chapter 10.
8.2 Str Ing S
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a letter,
digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single,
double or triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
str1, str2, str3, str4 are all string variables
having the same value 'Hello World!'. Values stored in
str3 and str4 can be extended to multiple lines using
triple codes as can be seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
“The great thing about a
computer notebook is that no
matter how much you stuff
into it, it doesn't get bigger or
heavier. ”
– Bill Gates
Chapter 8
Strings
In this chapter
» Introduction to
Strings
» String Operations
» Traversing a String
» Strings Methods
and Built-in
Functions
» Handling Strings
Ch 8.indd 175 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 176
8.2.1 Accessing Characters in a String
Each individual character in a string can be accessed
using a technique called indexing. The index specifies
the character to be accessed in the string and is written
in square brackets ([ ]). The index of the first character
(from left) in the string is 0 and the last character is n-1
where n is the length of the string. If we give index value
out of this range then we get an IndexError. The index
must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including
variables and operators but the expression must
evaluate to an integer.
#an expression resulting in an integer index
#so gives 6
th
character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers
Python allows an index value to be negative also.
Negative indices are used when we want to access the
characters of the string from right to left. Starting from
right hand side, the first character has the index as -1
and the last character has the index –n where n is the
length of the string. Table 8.1 shows the indexing of
characters in the string ‘Hello World!’ in both the cases,
i.e., positive and negative indices.
>>> str1[-1] #gives first character from right
'!'
>>> str1[-12]#gives last character from right
'H'
Python does not have
a character data type.
String of length one is
considered as character.
Ch 8.indd 176 08-Apr-19 12:39:21 PM
2024-25
String S 177
An inbuilt function len() in Python returns the length
of the string that is passed as parameter. For example,
the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'
8.2.2 String is Immutable
A string is an immutable data type. It means that
the contents of the string cannot be changed after it
has been created. An attempt to do this would lead to
an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment
8.3 Str Ing o perat Ion S
As we know that string is a sequence of characters.
Python allows certain operations on string data type,
such as concatenation, repetition, membership and
slicing. These operations are explained in the following
subsections with suitable examples.
8.3.1 Concatenation
To concatenate means to join. Python allows us to join
two strings using concatenation operator plus which is
denoted by symbol +.
Table 8.1 Indexing of characters in string 'Hello World!'
Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l l o W o r l d !
Negative Indices -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Ch 8.indd 177 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 178
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
#str1 and str2 remain same
>>> str1 #after this operation.
'Hello'
>>> str2
'World!'
8.3.2 Repetition
Python allows us to repeat the given string using
repetition operator which is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
'HelloHello'
#repeat the value of str1 5 times
>>> str1 * 5
'HelloHelloHelloHelloHello'
Note: str1 still remains the same after the use of
repetition operator.
8.3.3 Membership
Python has two membership operators 'in' and 'not
in'. The 'in' operator takes two strings and returns
True if the first string appears as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
The 'not in' operator also takes two strings and
returns True if the first string does not appear as a
substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
8.3.4 Slicing
In Python, to access some part of a string or substring,
we use a method called slicing. This can be done by
Ch 8.indd 178 08-Apr-19 12:39:21 PM
2024-25
Page 5
8.1 Introduct Ion We have studied in Chapter 5, that a sequence is an
orderly collection of items and each item is indexed by
an integer. Following sequence data types in Python
were also briefly introduced in Chapter 5.
• Strings
• Lists
• Tuples
Another data type ‘Dictionary’ was also introduced
in chapter 5 which falls under the category of mapping.
In this chapter, we will go through strings in detail.
List will be covered in Chapter 9 whereas tuple and
dictionary will be discussed in Chapter 10.
8.2 Str Ing S
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a letter,
digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single,
double or triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
str1, str2, str3, str4 are all string variables
having the same value 'Hello World!'. Values stored in
str3 and str4 can be extended to multiple lines using
triple codes as can be seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
“The great thing about a
computer notebook is that no
matter how much you stuff
into it, it doesn't get bigger or
heavier. ”
– Bill Gates
Chapter 8
Strings
In this chapter
» Introduction to
Strings
» String Operations
» Traversing a String
» Strings Methods
and Built-in
Functions
» Handling Strings
Ch 8.indd 175 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 176
8.2.1 Accessing Characters in a String
Each individual character in a string can be accessed
using a technique called indexing. The index specifies
the character to be accessed in the string and is written
in square brackets ([ ]). The index of the first character
(from left) in the string is 0 and the last character is n-1
where n is the length of the string. If we give index value
out of this range then we get an IndexError. The index
must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including
variables and operators but the expression must
evaluate to an integer.
#an expression resulting in an integer index
#so gives 6
th
character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers
Python allows an index value to be negative also.
Negative indices are used when we want to access the
characters of the string from right to left. Starting from
right hand side, the first character has the index as -1
and the last character has the index –n where n is the
length of the string. Table 8.1 shows the indexing of
characters in the string ‘Hello World!’ in both the cases,
i.e., positive and negative indices.
>>> str1[-1] #gives first character from right
'!'
>>> str1[-12]#gives last character from right
'H'
Python does not have
a character data type.
String of length one is
considered as character.
Ch 8.indd 176 08-Apr-19 12:39:21 PM
2024-25
String S 177
An inbuilt function len() in Python returns the length
of the string that is passed as parameter. For example,
the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'
8.2.2 String is Immutable
A string is an immutable data type. It means that
the contents of the string cannot be changed after it
has been created. An attempt to do this would lead to
an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment
8.3 Str Ing o perat Ion S
As we know that string is a sequence of characters.
Python allows certain operations on string data type,
such as concatenation, repetition, membership and
slicing. These operations are explained in the following
subsections with suitable examples.
8.3.1 Concatenation
To concatenate means to join. Python allows us to join
two strings using concatenation operator plus which is
denoted by symbol +.
Table 8.1 Indexing of characters in string 'Hello World!'
Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l l o W o r l d !
Negative Indices -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Ch 8.indd 177 08-Apr-19 12:39:21 PM
2024-25
Computer SCien Ce – Cla SS xi 178
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
#str1 and str2 remain same
>>> str1 #after this operation.
'Hello'
>>> str2
'World!'
8.3.2 Repetition
Python allows us to repeat the given string using
repetition operator which is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
'HelloHello'
#repeat the value of str1 5 times
>>> str1 * 5
'HelloHelloHelloHelloHello'
Note: str1 still remains the same after the use of
repetition operator.
8.3.3 Membership
Python has two membership operators 'in' and 'not
in'. The 'in' operator takes two strings and returns
True if the first string appears as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
The 'not in' operator also takes two strings and
returns True if the first string does not appear as a
substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
8.3.4 Slicing
In Python, to access some part of a string or substring,
we use a method called slicing. This can be done by
Ch 8.indd 178 08-Apr-19 12:39:21 PM
2024-25
String S 179
specifying an index range. Given a string str1, the
slice operation str1[n:m] returns the part of the string
str1 starting from index n (inclusive) and ending at m
(exclusive). In other words, we can say that str1[n:m]
returns all the characters starting from str1[n] till
str1[m-1]. The numbers of characters in the substring
will always be equal to difference of two indices m and
n, i.e., (m-n).
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]
If the first index is not mentioned, the slice starts
from index.
#gives substring from index 0 to 4
>>> str1[:5]
'Hello'
If the second index is not mentioned, the slicing is
done till the length of the string.
#gives substring from index 6 to end
>>> str1[6:]
'World!'
The slice operation can also take a third index that
specifies the ‘step size’. For example, str1[n:m:k],
means every k
th
character has to be extracted from
the string str1 starting from n and ending at m-1. By
default, the step size is one.
>>> str1[0:10:2]
'HloWr'
>>> str1[0:10:3]
'HlWl'
Negative indexes can also be used for slicing.
#characters at index -6,-5,-4,-3 and -2 are
#sliced
>>> str1[-6:-1]
Ch 8.indd 179 21-May-19 12:26:40 PM
2024-25
Read More