Computer Science: XI
Chapter 8
Python Strings:
1. Introduction to Strings
A string in Python is defined as "a sequence which is made up of one or more UNICODE characters." These characters
can include letters, digits, whitespace, or any other symbol. Strings are a fundamental data type in Python, along with
lists, tuples, and dictionaries.
1.1 Creating Strings
Strings can be created by enclosing one or more characters within:
Single quotes: str1 = 'Hello World!'
Double quotes: str2 = "Hello World!"
Triple single or double quotes: str3 = """Hello World!""" or str4 = '''Hello World!'''
Triple quotes are particularly useful as they allow strings to "be extended to multiple lines."
1.2 Immutability of Strings
A critical characteristic of strings in Python is their immutability. This means that "the contents of the string cannot be
changed after it has been created." Any attempt to modify a character at a specific index will result in a TypeError. For
example:
>>> str1 = "Hello World!"
>>> str1[1] = 'a'
TypeError: 'str' object does not support item assignment
2. Accessing Characters (Indexing)
Individual characters within a string can be accessed using indexing.
2.1 Positive Indexing
The first character in a string is at index 0.
The last character is at index n-1, where n is the length of the string.
Accessing an index outside this range will raise an IndexError.
Indices must be integers; using a float will result in a TypeError.
Example:
>>> str1 = 'Hello World!'
>>> str1[0]
'H'
>>> str1[6]
'W'
>>> str1[11]
'!'
2.2 Negative Indexing
Python also supports negative indexing, which allows access to characters from right to left.
The first character from the right (last character of the string) has an index of -1.
The last character from the right (first character of the string) has an index of -n, where n is the length of the
string.
Example:
>>> str1 = 'Hello World!'
>>> str1[-1]
'!'
>>> str1[-12]
'H'
2.3 len() Function
The built-in len() function returns the length of a string.
>>> str1 = 'Hello World!'
>>> len(str1)
12
3. String Operations
Python provides several operations that can be performed on strings:
3.1 Concatenation
Strings can be joined together using the + operator.
>>> str1 = 'Hello'
>>> str2 = 'World!'
>>> str1 + str2
'HelloWorld!'
It's important to note that "str1 and str2 remain same after this operation."
3.2 Repetition
The * operator allows a string to be repeated a specified number of times.
>>> str1 = 'Hello'
>>> str1 * 2
'HelloHello'
Similar to concatenation, the original string str1 "still remains the same after the use of repetition operator."
3.3 Membership Operators (in, not in)
The in operator returns True if the first string appears as a substring within the second string, otherwise False.
>>> 'W' in str1
True
>>> 'My' in str1
False
The not in operator returns True if the first string does not appear as a substring in the second string, otherwise
False.
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
3.4 Slicing
Slicing is a technique used to "access some part of a string or substring." It involves specifying an index range using
square brackets [n:m].
str1[n:m] returns the substring starting from index n (inclusive) and ending at m (exclusive). The number of
characters returned is m-n.
>>> str1 = 'Hello World!'
>>> str1[1:5]
'ello'
If the first index n is omitted (str1[:m]), the slice starts from index 0.
>>> str1[:5]
'Hello'
If the second index m is omitted (str1[n:]), the slice goes till the end of the string.
>>> str1[6:]
'World!'
A third index k can be added (str1[n:m:k]) to specify a 'step size', extracting every kth character. The default step
size is one.
>>> str1[0:10:2]
'HloWr'
Negative indices can also be used for slicing.
>>> str1[-6:-1]
'World'
A step size of -1 without n or m (str1[::-1]) will reverse the string.
>>> str1[::-1]
'!dlroW olleH'
4. Traversing a String
Each character of a string can be accessed sequentially, or traversed, using loops.
4.1 Using for Loop
The for loop iterates directly over each character in the string.
>>> str1 = 'Hello World!'
>>> for ch in str1:
... print(ch,end = '')
Hello World!
"The loop starts from the first character of the string str1 and automatically ends when the last character is accessed."
4.2 Using while Loop
The while loop can be used by maintaining an index and incrementing it until it reaches the string's length.
>>> str1 = 'Hello World!'
>>> index = 0
>>> while index < len(str1):
... print(str1[index],end = '')
... index += 1
Hello World!
5. String Methods and Built-in Functions
Python offers numerous built-in functions and string methods for manipulation. Some key examples include:
Functions
User-defined functions can be created to perform specific string operations, demonstrating practical application of the
concepts.
6.1 Counting Character Occurrences
A function can count how many times a given character appears in a string.
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
Example Output:
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3
6.2 Replacing Vowels
A function can replace all vowels in a string with a specified character (e.g., *).
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
Example Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
6.3 Reversing a String
Strings can be reversed either by iterating through them in reverse order (without creating a new string) or by building a
new reversed string.
Reverse without new string:
st = input("Enter a string: ")
for i in range(-1,-len(st)-1,-1):
print(st[i],end='')
Example Output: dlroW olleH
Reverse with new string:
def reverseString(st):
newstr = ''
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
Example Output: The reversed String is: dlroW olleH
6.4 Palindrome Check
A function can determine if a string is a palindrome (reads the same forwards and backwards).
def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
Example Output:
Enter a String: kanak
The given string kanak is a palindrome
The given string computer is not a palindrome
Enter a String: computer
Python allows several operations on string data types, which are detailed in "Python Strings: A Comprehensive Guide".
These operations include concatenation, repetition, membership, and slicing.
Here's a detailed discussion of each:
Concatenation (Section 8.3.1)
o To concatenate means to join.
o Python uses the + operator to join two strings.
o Example: If str1 = 'Hello' and str2 = 'World!', then str1 + str2 results in 'HelloWorld!'.
o It's important to note that the original strings (str1 and str2) remain unchanged after this operation.
Repetition (Section 8.3.2)
o Python allows a given string to be repeated using the * operator.
o Example: If str1 = 'Hello', then str1 * 2 results in 'HelloHello', and str1 * 5 results in
'HelloHelloHelloHelloHello'.
o Similar to concatenation, the original string (str1) remains the same after using the repetition operator.
Membership (Section 8.3.3)
o Python provides two membership operators: in and not in.
o 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.
Example: 'W' in 'Hello World!' returns True, while 'My' in 'Hello World!' returns False.
o 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, it returns False.
Example: 'My' not in 'Hello World!' returns True, whereas 'Hello' not in 'Hello World!' returns
False.
Slicing (Section 8.3.4)
o Slicing is a method used to access a part of a string or substring by specifying an index range.
o Basic Slicing (str[n:m]): This operation returns the part of the string str1 starting from index n (inclusive)
and ending at m (exclusive). The number of characters in the substring will be m - n.
Example: If str1 = 'Hello World!', then str1[1:5] returns 'ello', and str1[7:10] returns 'orl'.
If the first index n is greater than the second index m, an empty string ('') is returned.
o Omitting Indices:
If the first index is omitted (str[:m]), the slice starts from index 0.
Example: str1[:5] returns 'Hello'.
If the second index is omitted (str[n:]), the slice extends to the end of the string.
Example: str1[6:] returns 'World!'.
o Step Size (str[n:m:k]): A third index k can be added to specify the "step size". This means every kth
character is extracted from the string str1, starting from n and ending at m-1. The default step size is
one.
Example: str1[0:10:2] returns 'HloWr'.
o Negative Indices in Slicing: Negative indices can also be used for slicing.
Example: str1[-6:-1] returns 'World'.
o Reversing a String with Slicing: A powerful application of slicing is reversing a string by ignoring both
indexes and using a step size of -1 (str[::-1]).
Example: str1[::-1] returns '!dlroW olleH'.
built-in functions and methods string:
len()
o Description: Returns the length of the given string.
o Example: len('Hello World!') returns 12.
title()
o Description: Returns the string with the first letter of every word in uppercase and the rest in
lowercase.
o Example: 'hello WORLD!'.title() returns 'Hello World!'.
lower()
o Description: Returns the string with all uppercase letters converted to lowercase.
o Example: 'hello WORLD!'.lower() returns 'hello world!'.
upper()
o Description: Returns the string with all lowercase letters converted to uppercase.
o Example: 'hello WORLD!'.upper() returns 'HELLO WORLD!'.
count(str, start, end)
o Description: Returns the number of times a substring (str) occurs in the given string. If start and end
indices are not provided, searching begins from index 0 and ends at the length of the string.
o Example:
'Hello World! Hello Hello'.count('Hello', 12, 25) returns 2.
'Hello World! Hello Hello'.count('Hello') returns 3.
find(str, start, end)
o Description: Returns the first occurrence of the index of the substring (str) in the given string. If start
and end are not provided, searching starts from index 0. If the substring is not found, the function
returns -1.
o Example:
'Hello World! Hello Hello'.find('Hello', 10, 20) returns 13.
'Hello World! Hello Hello'.find('Hee') returns -1.
index(str, start, end)
o Description: Similar to find(), but raises a ValueError exception if the substring is not present in the
given string.
o Example:
'Hello World! Hello Hello'.index('Hello') returns 0.
'Hello World! Hello Hello'.index('Hee') raises ValueError: substring not found.
endswith(substring)
o Description: Returns True if the string ends with the supplied substring, otherwise returns False.
o Example:
'Hello World!'.endswith('World!') returns True.
'Hello World!'.endswith('lde') returns False.
startswith(substring)
o Description: Returns True if the string starts with the supplied substring, otherwise returns False.
o Example:
'Hello World!'.startswith('He') returns True.
'Hello World!'.startswith('Hee') returns False.
isalnum()
o Description: Returns True if all characters in the string are either alphabets or numeric. Returns False if
whitespace, special symbols, or an empty string is present.
o Example:
'HelloWorld'.isalnum() returns True.
'HelloWorld!!'.isalnum() returns False.
islower()
o Description: Returns True if the string is non-empty and has all lowercase alphabets, or has at least one
lowercase alphabet and the rest are non-alphabet characters.
o Example:
'hello world!'.islower() returns True.
'Hello World!'.islower() returns False.
isupper()
o Description: Returns True if the string is non-empty and has all uppercase alphabets, or has at least one
uppercase character and the rest are non-alphabet characters.
o Example:
'HELLO WORLD!'.isupper() returns True.
'Hello World!'.isupper() returns False.
isspace()
o Description: Returns True if the string is non-empty and all characters are white spaces (including blank,
tab, newline, carriage return).
o Example:
' \n \t \r'.isspace() returns True.
'Hello \n'.isspace() returns False.
istitle()
o Description: Returns True if the string is non-empty and in title case (first letter of every word is
uppercase, rest are lowercase).
o Example:
'Hello World!'.istitle() returns True.
'hello World!'.istitle() returns False.
lstrip()
o Description: Returns the string after removing spaces only from the left of the string.
o Example: ' Hello World! '.lstrip() returns 'Hello World! '.
rstrip()
o Description: Returns the string after removing spaces only from the right of the string.
o Example: ' Hello World!'.rstrip() returns ' Hello World!'.
strip()
o Description: Returns the string after removing spaces from both the left and the right of the string.
o Example: ' Hello World!'.strip() returns 'Hello World!'.
replace(oldstr, newstr)
o Description: Replaces all occurrences of an old string with a new string.
o Example:
'Hello World!'.replace('o', '*') returns 'Hell* W*rld!'.
'Hello World! Hello'.replace('Hello', 'Bye') returns 'Bye World! Bye'.
join(iterable)
o Description: Returns a string in which the characters from an iterable (like a string) have been joined by
a separator.
o Example: '-'.join('HelloWorld!') returns 'H-e-l-l-o-W-o-r-l-d-!'.
partition(separator)
o Description: Partitions the string at the first occurrence of the substring (separator) and returns a tuple
of three parts: (1) substring before the separator, (2) the separator itself, and (3) substring after the
separator. If the separator is not found, it returns the whole string and two empty strings.
o Example:
'India is a Great Country'.partition('is') returns ('India ', 'is', ' a Great Country').
'India is a Great Country'.partition('are') returns ('India is a Great Country', ' ', ' ').
split(delimiter)
o Description: Returns a list of words delimited by the specified substring. If no delimiter is given, words
are separated by space.
o Example:
'India is a Great Country'.split() returns ['India', 'is', 'a', 'Great', 'Country'].
'India is a Great Country'.split('a') returns ['Indi', ' is ', ' Gre', 't Country'].