Introduction to Python Programming (MBABA313)
MODULE 3
STRINGS
String or String Literal
A string is sequence of characters. The string begins and ends with a single
quote or double quote or triple quotes.
Double Quotes
Strings can begin and end with double
quotes.
In the below example the string begins with a double quote, Python knows that
the single quote is part of the string and not marking the end of the string.
Multiline Strings with Triple Quotes
A multiline string in Python begins and ends with either three single quotes or
three double quotes.
Any quotes, tabs, or newlines in between the “triple quotes” are considered part
of the string. Python’s indentation rules for blocks do not apply to lines inside
a multiline string.
3.1 Length
The len() function returns the number of characters in a string.
syntax
len(string)
3.2 Working with the parts of a string
The integer inside the square brackets that follows the string name is called an
index.
The first character in the string is at index 0, the second character is at index 1,
and so on.
In the Python code we get IndexError if we give index more than length of string
-1.
Indexes can be only integer values. In the Python code we get TypeError if we give
float as index.
syntax
string[index]
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 1
Introduction to Python Programming (MBABA313)
String m a n g o
fruit
Index fruit[0] fruit[1] fruit [2] fruit [3] fruit [4]
Negative Index fruit [-5] fruit [-4] fruit [-3] fruit [-2] fruit [-1]
Enter the following into the interactive shell:
Negative Indexing:
Negative indexing means starts from the end of string. The integer value -1 refers
to the last character in a string, the value -2 refers to the second-to-last
character in a string, and so on.
Enter the following into the interactive shell:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 2
Introduction to Python Programming (MBABA313)
The enumerate() built -in function can be used to know the indices of characters
in a string.
3.3 Slices
A substring of a string is obtained by taking a slice
A slice has two or three integers separated by a colon typed between square
brackets.
syntax
string [start:stop:step]
The slice starts at Start index (included) and ends at Stop index (excluded).
Enter the following into the interactive shell:
As a shortcut, we can leave out one or both of the indices on either side of the
colon in the slice.
Leaving out the first index is the same as using 0, or the beginning of
the string.
Leaving out the second index is the same as using the length of the
string, which will slice to the end of the string.
Enter the following into the interactive shell:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 3
Introduction to Python Programming (MBABA313)
#Program to check whether given string is palindrome or not
Output 1:
Output 2:
3.4 Working with strings as single things
i) The upper() Method
Converts all the letters in a string into uppercase and nonletter characters
remain unchanged.
syntax
[Link]()
ii)The lower() Method
Converts all the letters in a string into lowercase and nonletter characters
remain unchanged.
syntax
[Link]()
iii)The title() Method
Converts a string into title i.e. makes the first letter in each word upper case.
syntax
[Link]()
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 4
Introduction to Python Programming (MBABA313)
iv) The capitalize() Method
Converts the first letter in a string into an uppercase followed by lowercase
letters.
syntax
[Link]()
v) The isupper() Method
Returns True if all the letters in a string are uppercase. Otherwise, False.
syntax:
[Link]()
vi) The islower() Method
Returns True if all the letters in a string are lowercase. Otherwise, False.
syntax
[Link]()
vii)The isalpha() Method
Returns True if a string consists only letters. Otherwise, False.
syntax:
[Link]()
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 5
Introduction to Python Programming (MBABA313)
viii)The isdigit() Method
Returns True if a string consists only numbers. Otherwise, False.
syntax
[Link]()
ix)The isdecimal() Method
Returns True if a string consists only numbers. Otherwise, False.
syntax
[Link]()
x)The isnumeric() Method
Returns True if a string consists only numbers. Otherwise, False.
syntax
[Link]()
xi)The isalnum() Method
Returns True if the string consists only letters or numbers or both letters and
numbers. Otherwise, False.
syntax
[Link]()
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 6
Introduction to Python Programming (MBABA313)
xii) The isspace() Method
Returns True if a string consists only spaces, tabs, and newlines. Otherwise,
False.
syntax
[Link]()
xiii) The istitle() Method
Returns True in a string if first letter of each word is uppercase.
syntax
[Link]()
xiv)The count() Method
Returns the number of times a specified value occurs in a string.
syntax
[Link](substring, start, stop)
substring- we want to count. It is required.
start- index position in the string where search should start. It is optional.
Default it is 0.
stop- index position in the string where search should stop. It is optional.
Default it is length of the string.
xv)The ljust() Method
Returns a left justified version of the string.
syntax
[Link](length, character)
The first argument is an integer length for the justified string. It is required.
The second argument is a character to fill the missing space. It is optional.
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 7
Introduction to Python Programming (MBABA313)
xvi)The rjust() Method
Returns a right justified version of the string.
syntax
[Link](length, character)
The first argument is an integer length for the justified string. It is required.
The second argument is a character to fill the missing space. It is optional.
xvii) The center() Method
Returns a centered string.
syntax
[Link](length, character)
The first argument is an integer length for the justified string. It is required.
The second argument is a character to fill the missing space. It is optional.
xviii)The lstrip() Method
Returns a left trimmed version of the string.
syntax
[Link](character)
A character or characters to remove. It is optional.
xix) The rstrip() Method
Returns a right trimmed version of the string.
syntax
[Link](character)
A character or characters to remove. It is optional.
xx) The strip() Method
Returns a trimmed version of the string.
syntax
[Link](character)
A character or characters to remove. It is optional.
xxi)The join() Method
The join() method takes all items in an iterable and joins them into one string.
syntax
[Link](iterable)
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 8
Introduction to Python Programming (MBABA313)
xxii) The partition() Method
The partition() method searches for a specified string, and splits the string into
a tuple containing three elements.
The first element contains the part before the separator.
The second element contains the separator.
The third element contains the part after the separator.
syntax
[Link](separator)
xxiii)The startswith() Method
Return True if the string starts with the specified value. Otherwise, False.
syntax
[Link](value, start, stop)
value-the specified value to check if the string startswith. It is required.
start- index position in the string where search should start. It is
optional. Default it is 0.
stop- index position in the string where search should stop. It is optional.
Default it is length of the string.
xxiv) The endswith() Method
Return True if the string ends with the specified value. Otherwise, False.
syntax
[Link](value, start, stop)
value-the specified value to check if the string startswith. It is required.
start- index position in the string where search should start. It is
optional. Default it is
stop- index position in the string where search should stop. It is
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 9
Introduction to Python Programming (MBABA313)
optional. Default it is length of the string.
xxv)The index() Method
It finds the first occurrence of the specified value. The index() method returns
ValueError error message if the value is not found.
syntax
[Link](value, start, end)
value-the specified value to check its index. It is required.
start- index position in the string where search should start. It is optional.
Default it is 0.
stop- index position in the string where search should stop. It is optional.
Default it is length of the string.
xxvi) The replace() Method
Replaces a specified phrase with another specified phrase.
syntax
[Link](oldvalue, newvalue, count)
oldvalue - It is required. The string to be replaced.
newvalue - It is required. The string to replace the old
count- It is optional. The number of occurrences the old value to be
replaced. Default all occurrences.
xxvii) The swapcase() Method
Returns a a new string where all the uppercase characters in the original string
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 10
Introduction to Python Programming (MBABA313)
are converted to lowercase and vice versa.
syntax
[Link]()
#Program to change lower case letters into upper case and vice versa.
Output 1:
Output 2:
3.5 Traversal and the for loop
String Traversal operations refers to processing a string one character at a time.
We start at the beginning, select each character in turn, do something to it, and
continue until the end.
i) Traversal using while statement
Output:
The while loop and an index variable are used to manually track the current
position within the string. It starts with index = 0 and character ‘m’. The loop
condition is index < len(fruit), so when index is equal to the length of the string,
the condition is False, and the body of the loop is not executed.
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 11
Introduction to Python Programming (MBABA313)
ii) Traversal using for loop
Output:
The for loop directly iterates over each character in the string. Each time through
the loop, the next character in the string is assigned to the variable. The loop
continues till the end of string.
Output:
3.6 String comparison
Python supports several operators for string comparison, including ==, !=, <, <=,
>, and >=. These operators allow for both equality and lexicographical
(alphabetical order) comparisons, which is useful when sorting or arranging
strings.
All the uppercase letters come before all the lowercase letters.
Output 1:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 12
Introduction to Python Programming (MBABA313)
Output 2:
Output 3:
Output 4:
3.7 Strings are immutable
Strings are immutable, which means we can’t change an existing string. Trying
to change existing string returns TypeError.
ex1:
ex2:
But in the above ex1 we can create a new string using
3.8 The in and not in operators
An expression with in or not in will evaluate to a Boolean True or False.
The in operator
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 13
Introduction to Python Programming (MBABA313)
The not in operator
# program to remove all the vowels from a string
Output 1:
Output 2:
3.9 A find function
The find function takes a character and finds the index where that character
appears.
Output:
If character == letter, the function returns immediately, breaking out of
the loop prematurely.
If the character doesn’t appear in the string, then the program exits the
loop normally and returns -1.
This pattern of computation is sometimes called a eureka traversal or
short-circuit evaluation.
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 14
Introduction to Python Programming (MBABA313)
3.10 Optional parameters
To find the locations of the second or third occurrence of a character in a string,
we can modify the find function, adding a third (optional) parameter for the
starting position in the search string.
Output:
The find function takes a character and finds the index where that
character appears.
The third parameter indicates the starting index of search. In the above
example search starts from index 2.
If character == letter, the function returns immediately, breaking out of
the loop prematurely.
If the character doesn’t appear in the string, then the program exits the
loop normally and returns -1.
We can add another optional parameter
Output:
The semantics of start and end in this function are precisely the same as they
are in the range function.
3.11 Looping and counting
#program to count character ‘a’ in ‘banana’
Output:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 15
Introduction to Python Programming (MBABA313)
#program that accepts a sentence and find the number of characters,
letters, digits, and special characters.
Output:
3.12 The built-in find method
The built in find() method finds the first occurrence of the specified value. This
method returns -1 if the value is not found.
syntax
[Link](value, start, stop)
value – It is required. The value to search for.
start- It is optional. Where to start the search. Default is 0.
stop- It is optional. Where to end the search. Default is to the end of the
string.
It can find index of substrings, not just single characters.
3.13 The split() method
The split() method splits a string into a list. It splits a single multi-word string
into a list of individual words, removing all the whitespace between them.
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 16
Introduction to Python Programming (MBABA313)
syntax
[Link](separator, maxsplit)
separator- It is optional. Specifies the separator to use when splitting the
string. By default any whitespace is a separator
maxsplit- It is optional. Specifies how many splits to do. Default value is
1.
3.14 Cleaning up your strings
#Program to remove all punctuations from the sentence
Output:
Setting up that first assignment in the above program is messy and error-prone.
Fortunately, the Python string module already does it for us. So we will import
the string module.
Output:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 17
Introduction to Python Programming (MBABA313)
3.15 The string format method
The template string contains place holders {0}, {1}, {2} ...etc. The format method
substitutes its arguments into the place holders. The numbers in the place
holders are indexes that determine which argument gets substituted.
ex1:
ex2:
ex3:
ex4:
ex5:
#The program prints out a table of various powers of the numbers from1 to
5. In its current form it relies on the tab character(\t) to align the columns
of values.
Output:
The best solution would be to set the width of each column independently using
string formatting.
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 18
Introduction to Python Programming (MBABA313)
Output:
Chandrakala S, Asst. Professor, SJCIT, Chickballapur 19