Strings: Working with strings as single things, working with the parts of a string,
length, Traversal and the for loop, slices, string comparison, strings are immutable, the
in and not in operators, A find function, looping and counting, Optional parameters,
The built-in find method, The split method, Cleaning up your strings, The String format
method
A string is a sequence of characters enclosed in quotes. It can include letters, numbers,
symbols or spaces. Since Python has no separate character type, even a single character is
treated as a string with length one. Strings are widely used for text handling and
manipulation.
Creating a String
Strings can be created using either single ('...') or double ("...") quotes. Both behave the
same.
Example: Creating two equivalent strings one with single and other with double quotes.
s1 = 'Navkis' # single quote
s2 = "Navkis" # double quote
print(s1)
print(s2)
Multi-line Strings
Use triple quotes ('''...''' ) or ( """...""") for strings that span multiple lines. Newlines are
preserved.
Example: Define and print multi-line strings using both styles.
s = """I am Learning
Python String """
print(s)
s = '''I'm a
Studying in Navkis'''
print(s)
Accessing characters in String
Strings are indexed sequences. Positive indices start at 0 from the left; negative indices start
at -1 from the right as represented in below image:
0 1 2 3 4 5 6
C O L L E G E
-7 -6 -5 -4 -3 -2 -1
Example 1: Access specific characters through positive indexing.
s = "Navkis"
print(s[0]) # first character
print(s[4]) # 5th character
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.
Example 2: Read characters from the end using negative indices.
s = "Navkis College of Engineering"
print(s[-10]) # 3rd character
print(s[-5]) # 5th character from end
String Length: To find length of string we use len() function
Eg:
Method1:
a="Navkis"
length=len(a)
print(length)
Method2:
a = "Navkis"
print(len(a))
Method3:
print(len("Navkis"))
Traversal and the for loop:
String Traversal operations refers to process of one character at a time. Often we start at the
beginning, select each character in turn, do something to it, and continue until the end.
Method 1: Using For Loops
• Initialize a variable with the string you want to traverse.
• Use a for loop to iterate over each character in the string.
• In each iteration, the loop variable holds the current character.
• You can print or process the character within the loop.
text = "Hello, World!"
for char in text:
print(char)
Method 2: Using a While Loop
• Initialize a variable with the string you want to traverse.
• Initialize an index variable (e.g., index) to 0.
• Use a while loop that continues as long as the index is less than the length of the
string.
• Within the loop, access the character at the current index and process it.
• Increment the index after processing the character to move to the next character.
For Example:
text = "Hello, World!"
index = 0
while index < len(text):
print(text[index])
index += 1
String Slicing
Slicing is a way to extract a portion of a string by specifying the start and end indexes. The
syntax for slicing is string[start:end], where start starting index and end is stopping index
(excluded).
Example: In this example we are slicing through range and reversing a string.
s = "College"
print(s[1:4]) # characters from index 1 to 3
print(s[:3]) # from start to index 2
print(s[3:]) # from index 3 to end
print(s[::-1]) # reverse string
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.
example to illustrate these operators.
s1 = "apple"
s2 = "banana"
# "apple" is not equal to "banana", therefore it is False
print(s1 == s2)
# "apple" is different from "banana", therefore it is True
print(s1 != s2)
# "apple" comes before "banana" lexicographically, therefore it is True
print(s1 < s2)
Output
False
True
True
Explanation:
• == checks if two strings are identical.
• != checks if two strings differ.
• <, <=, >, >= perform lexicographical comparisons based on alphabetical order.
== Operator for Equality Check
The == operator is a simple way to check if two strings are identical. If both strings are
equal, it returns True; otherwise, it returns False.
s1 = "Python"
s2 = "Python"
# Since both strings are identical, therefore it is True
print (s1 == s2)
Output
True
Explanation: In this example, since s1 and s2 have the same characters in the same order, so
== returns True.
!= Operator for Inequality Check
The != operator helps to verify if two strings are different. If the strings are different then it
will return True, otherwise returns False.
s1 = "Python"
s2 = "Java"
# "Python" is different from "Java", therefore it is True
print(s1 != s2)
Output
True
Explanation: Here, != checks that s1 and s2 are not the same, so it returns True.
Lexicographical comparison checks if one string appears before or after another in
alphabetical order. This is especially useful for sorting.
s1 = "apple"
s2 = "banana"
# "apple" appears before "banana" alphabetically, therefore it is True
print(s1 < s2)
# "banana" comes after "apple", therefore it is True
print(s2 > s1)
Output
True
True
Explanation: The < and > operators are used to find the order of s1 and s2 lexicographically.
This method ideal for sorting and alphabetical comparisons.
Case-Insensitive Comparison
Strings in Python can be compared case-insensitively by converting both strings to
either lowercase or uppercase.
s1 = "Apple"
s2 = "apple"
# Both strings are same ignoring case, therefore it is True
print([Link]() == [Link]())
Output
True
Explanation: Converting both strings to lowercase (or uppercase) before comparison
Using startswith() and endswith() Methods
The startswith() and endswith() methods in Python are used to check if a string begins or ends
with a specific substring.
s = "hello world"
# 's' starts with "hello", therefore it is True
print([Link]("hello"))
# 's' ends with "world", therefore it is True
print([Link]("world"))
Output
True
True
Explanation: These methods are helpful for conditional checks based on prefixes or suffixes
in a string.
String Immutability
Strings are immutable, which means that they cannot be changed after they are created. If we
need to manipulate strings then we can use methods like concatenation,
slicing or formatting to create new strings based on original.
Example: In this example we are changing first character by building a new string.
s = "College"
s = "C" + s[1:] # create new string
print(s)
Output
College
Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
Example: Here, we are using del keyword to delete a string.
s = "College"
del s
Note: After deleting the string if we try to access s then it will result in a NameError because
variable no longer exists.
Updating a String
As strings are immutable, “updates” create new strings using slicing or methods such
as replace().
Example: This code fix the first letter and replace a word.
s = "navkis College"
s1 = "N" + s[1:] # update first character
s2 = [Link]("College", "College of Engineering") # replace word
print(s1)
print(s2)
Output:
Navkis College
navkis College of Engineering
Common String Methods
Python provides various built-in methods to manipulate strings. Below are some of the most
useful methods:
len():
upper() and lower():
strip() and replace(): strip() removes leading and trailing whitespace from the string and
replace() replaces all occurrences of a specified substring with another.
s = " College "
print([Link]())
s = "Python is fun"
print([Link]("fun", "awesome"))
Ouput:
College
Python is awesome
Concatenating and Repeating Strings
We can concatenate strings using + operator and repeat them using * operator.
1. Strings can be combined by using + operator.
Example: Join two words with a space.
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)
Output
Hello World
2. We can repeat a string multiple times using * operator.
Example: Repeat a greeting three times.
s = "Hello "
print(s * 3)
Output
Hello Hello Hello
Python Membership and Identity Operators
Membership and Identity operators help us check relationships between values and objects.
They are mainly used to test whether a value exists within a sequence or whether two
variables refer to same object in memory.
Membership Operators
The Membership operators test for the membership of an object in a sequence, such as
strings, lists or tuples. Python offers two membership operators to check or validate the
membership of a value. They are as follows:
1. IN Operator
The in operator returns True if the given element exists inside a sequence, otherwise it returns
False.
Example: Checking elements in different sequences
str1 = "Hello World"
print('O' in str1) # checking character in a string
print('H' in str1) # checking character in a string
Output
False
True
Explanation:
• 'O' in str1: False because Python is case-sensitive ('O' ≠ 'o').
NOT IN Operator
The not in operator is the opposite it returns True if the element is not found in a sequence.
Example: Using not in with string
str1 = "Hello World"
print('O' not in str1) # checking character in a string
print('H' not in str1) # checking character in a string
Output:
True
False
Explanation:
• 'O' not in str1: True because 'O' is missing.
[Link]() Method
Python also provides a function from the operator module called contains() that works like in.
Syntax:
[Link](sequence, value)
Example: Using [Link]() with different sequences
import operator
print([Link]("Hello World", 'O')) # string
Output:
False
Identity Operators
The Identity Operators are used to compare the objects if both objects are actually of same
data type and share same memory location. There are different identity operators such as:
1. IS Operator
The is operator checks if two variables point to the same object (same memory location).
Example: Comparing different objects
s1 = "hello world"
s2 = "hello world"
print(s1 is s2) # strings
Output:
True
Explanation:
• s1 is s2: True because Python reuses identical string objects.
IS NOT Operator
The opposite of is. It checks if two variables point to different objects.
Example: Checking with is not
s1 = "hello world"
s2 = "hello world"
print(s1 is not s2) # strings
output:
False
Difference Between == and is
While comparing objects in Python, users often gets confused between Equality operator and
Identity operator. The equality operator is used to compare value of two variables, whereas
identities operator is used to compare memory location of two variables.
Example: In this code we have two lists that contains same data, we used 'is' operator and
'==' operator to compare both lists.
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # identity check
print(a == b) # value check
Output
False
True
Explanation:
• a == b: True because the contents are the same.
• a is b: False because they are stored as separate list objects.
A find function:
find() method returns the index of the first occurrence of a substring within a given string. If
the substring is not found, it returns -1. This method is case-sensitive, which means "abc" is
treated differently from "ABC". Example:
s = "Welcome to College!"
index = [Link]("College")
print(index)
Output
11
Syntax of find() method
[Link](substring, start, end))
Parameter:
• substring: The substring to search for within the main string s.
• start (optional): The starting index from where to begin the search.
• end (optional): The ending index where the search should stop.
Return Value:
• Returns the first index of the substring if it is found within the specified range.
• Returns -1 if the substring is not found.
Examples of find() method
Example 1: We can limit the search to a specific portion of the string by
providing start and end parameters.
s = "abc abc abc"
index = [Link]("abc", 4)
print(index)
Output
4
Explanation:
• The search starts from index 4, skipping the first "abc".
• The next occurrence of "abc" is found at index 8.
Example 2: The find() method is case-sensitive, so uppercase and lowercase letters are
treated differently.
s = "Python is fun"
index = [Link]("python")
print(index)
Output
-1
Explanation: Since "python" (lowercase) does not match "Python" (uppercase), the method
returns -1.
Example 3: In this example, we are searching for the first occurrence of a substring "abc" in
a string that contains multiple spaces between the words.
s = "abc abc abc"
res = [Link]("abc")
print(res)
Output
0
Explanation: The substring "abc" starts at index 0 in the string "abc abc abc", so find()
returns 0.
find() vs index()
Both find() and index() methods locate a substring within a string. However, they differ in
behavior when the substring is not found.
• find() returns the index or -1 if not found
• index() same as find(), but raises a ValueError if not found
looping and counting,
Optional parameters,
The built-in find method,
The split method,
Cleaning up your strings: we’ll often work with strings that contain punctuation, or tab and
new line characters. We’d prefer to strip off these unwanted characters. Strings are
immutable, so we cannot change the string with the punctuation – we need to travers the
original string and create a new string, omitting any punctuation.
Punctation = “!\”#$%&’()*+-,/:;< = >?@[\\]^_`{|}~”
Formatting Strings
Python provides several ways to include variables inside strings.
1. Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
Example: Embed variables directly using {} placeholders.
name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")
Output
Name: Alice, Age: 22
2. Using format()
Another way to format strings is by using format() method.
Example: Use placeholders {} and pass values positionally.
s = "My name is {} and I am {} years old.".format("Alice", 22)
print(s)
Output
My name is Alice and I am 22 years old.
program that counts the number of vowels (a, e, i, o, u) in a given string:
python
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
# Example usage
input_string = input("Enter a string: ")
vowel_count = count_vowels(input_string)
print("Number of vowels:", vowel_count)
Tuple: Tuples are used for grouping data, Tuple assignment, Tuples as return values,
composability of data
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example: Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the tuple:
Example
This example returns the items from "cherry" and to the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Lists
a list is a built-in data structure that can hold an ordered collection of items. Unlike arrays in
some languages, Python lists are very flexible:
• Can contain duplicate items
• Mutable: items can be modified, replaced, or removed
• Ordered: maintains the order in which items are added
• Index-based: items are accessed using their position (starting from 0)
• Can store mixed data types (integers, strings, booleans, even other lists)
Creating a List
Lists can be created in several ways, such as using square brackets, the list() constructor or by
repeating elements. Let's look at each method one by one with example:
1. Using Square Brackets
We use square brackets [] to create a list directly.
a = [1, 2, 3, 4, 5] # List of integers
b = ['apple', 'banana', 'cherry'] # List of strings
c = [1, 'hello', 3.14, True] # Mixed data types
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Using list() Constructor
We can also create a list by passing an iterable (like a tuple, string or another list) to
the list() function.
a = list((1, 2, 3, 'apple', 4.5))
print(a)
b = list("Navkis")
print(b)
Output
[1, 2, 3, 'apple', 4.5]
['N', 'a', 'v',’k’,’I’,’s’]
Creating List with Repeated Elements
We can use the multiplication operator * to create a list with repeated items.
a = [2] * 5
b = [0] * 7
print(a)
print(b)
Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list are accessed using indexing. Python indexes start at 0, so a[0] gives the first
element. Negative indexes allow access from the end (e.g., -1 gives the last element).
a = [10, 20, 30, 40, 50]
print(a[0])
print(a[-1])
print(a[1:4]) # elements from index 1 to 3
Output
10
50
[20, 30, 40]
Adding Elements into List
We can add elements to a list using the following methods:
• append(): Adds an element at the end of the list.
• extend(): Adds multiple elements to the end of the list.
• insert(): Adds an element at a specific position.
• clear(): removes all items.
a = []
[Link](10)
print("After append(10):", a)
[Link](0, 5)
print("After insert(0, 5):", a)
[Link]([15, 20, 25])
print("After extend([15, 20, 25]):", a)
[Link]()
print("After clear():", a)
0 1 2 3 4
5 10 15 20 25
Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
After clear(): []
Updating Elements into List
Since lists are mutable, we can update elements by accessing them via their index.
a = [10, 20, 30, 40, 50]
a[1] = 25
print(a)
Output
[10, 25, 30, 40, 50]
Removing Elements from List
We can remove elements from a list using:
• remove(): Removes the first occurrence of an element.
• pop(): Removes the element at a specific index or the last element if no index is
specified.
• del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]
[Link](30)
print("After remove(30):", a)
popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)
del a[0]
print("After del a[0]:", a)
Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
Iterating Over Lists
We can iterate over lists using loops, which is useful for performing actions on each item.
a = ['apple', 'banana', 'cherry']
for item in a:
print(item)
Output
apple
banana
cherry
Nested Lists
A nested list is a list within another list, which is useful for representing matrices or tables.
We can access nested elements by chaining indexes.
matrix = [ [1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
print(matrix[1][2])
1 [00] 2[01] 3[02]
4[10] 5[11] 6[12]
7[20] 8[21] 9[22]
Output
6
List Comprehension
List comprehension is a concise way to create lists using a single line of code. It is useful for
applying an operation or filter to items in an iterable, such as a list or range.
squares = [x**2 for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]
Explanation:
• for x in range(1, 6): loops through each number from 1 to 5 (excluding 6).
• x**2: squares each number x.
• [ ]: collects all the squared numbers into a new list.
How Python Stores List Elements?
In Python, a list doesn’t store actual values directly. Instead, it stores references (pointers) to
objects in memory. This means numbers, strings and booleans are separate objects in memory
and the list just keeps their addresses.
That’s why modifying a mutable element (like another list or dictionary) can change the
original object, while immutables remain unaffected.
a = [10, 20, "GfG", 40, True]
print(a)
print(a[0])
print(a[1])
print(a[2])
Output
[10, 20, 'GfG', 40, True]
10
20
GfG
Explanation:
• The list a contains an integer (10, 20 and 40), a string ("GfG") and a boolean (True).
• Elements are accessed using indexing (a[0], a[1], etc.).
• Each element keeps its original type.
Python List
Write a python program to create a list and perform the following operations.
i) Inserting an element
ii) Removing an element
iii) Appending an element
iv) Displaying the length of the list
v) Popping an element
num_elements = int(input("Enter the number of elements for your list: "))
my_list = []
for i in range(num_elements):
element = int(input(f"Enter element {i + 1}: "))
my_list.append(element)
new_element=int(input(“Enter new element to add”))
new_position=int(input(“Enter which position you need to add”))
my_list.insert(new_position, new_element) # Inserts 25 at index 2
print("After insertion:", my_list)
my_list.remove(20) # Removes the first occurrence of 20
print("After removal:", my_list)
my_list.append(50)
print("After appending:", my_list)
print("Length of the list:", len(my_list))
popped_element = my_list.pop()
print("Popped element:", popped_element)
print("List after popping:", my_list)