0% found this document useful (0 votes)
12 views17 pages

Python String Basics and Operations

The document covers fundamental concepts of strings, tuples, and lists in Python, detailing their properties, methods, and usage. It explains string immutability, tuple assignment, and list operations such as accessing elements, checking membership, and measuring length. Each section includes examples to illustrate the concepts effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

Python String Basics and Operations

The document covers fundamental concepts of strings, tuples, and lists in Python, detailing their properties, methods, and usage. It explains string immutability, tuple assignment, and list operations such as accessing elements, checking membership, and measuring length. Each section includes examples to illustrate the concepts effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

Module 02
Chapter 1 : Strings

1.1 Working with Strings as Single Things

 A string is a sequence of characters enclosed in quotes (single or double).


 Strings are treated as a single unit of data.
 Strings can include letters, digits, spaces, and special characters.
 Strings can be empty ("" or '').
 Strings can also span multiple lines using triple quotes (""" """ or ''' ''').
 Special characters like \n (newline) and \t (tab) can be included.
 Strings are widely used to represent text-based data.
 Strings are immutable, meaning they cannot be changed directly.
 Strings can be stored in variables and reused in programs.
 Strings are one of the most commonly used data types in Python.

Example :

s1 = "Hello World"
s2 = "Python123"
print(s1)
print(s2)

1.2 Working with Parts of a String

 Individual characters of a string can be accessed using indexing.


 Index starts from 0 for the first character.
 Negative indices can be used to access characters from the end.
 Accessing outside the index range causes an IndexError.
 Characters can be accessed using square brackets [ ].
 Strings behave like sequences, allowing indexed operations.
 Both positive and negative indexing can be combined with slices.
 Useful for checking or processing specific characters.
 Indexing cannot be used to change characters (since strings are immutable).
 Helps in string traversal and analysis.

Example

word = "Python"
print(word[0]) # P
print(word[-1]) # n

1.3 Length of a String

 The len() function returns the number of characters in a string.


 Spaces and special characters are also counted in the length.
 An empty string has a length of 0.
 The length helps in loops and string processing.
2

 Useful for password length validation and input checking.

 Can be used for slicing and traversal.


 Length does not change unless a new string is created.
 Common mistake: using [Link]() instead of len(string).
 Works on any sequence type, not just strings.
 Important in string analysis and operations.

Example (Indented)

word = "Python"
print(len(word)) # 6

1.4 Traversal and the for Loop

 Traversal means accessing each character in a string.


 The for loop can be used directly to iterate over characters.
 Index-based traversal uses range(len(string)).
 Traversal is useful for searching and counting.
 Nested loops allow processing multiple strings.
 Strings can be traversed in forward or reverse order.
 Traversal cannot modify string contents.
 Useful in encryption, frequency analysis, and pattern matching.
 Helps in input validation and string comparison.
 Essential for any string processing task.

Example (Indented)

for ch in "Python":
print(ch)

1.5 Slices

 A slice extracts a part of a string.


 Syntax: string[start:end:step].
 Omitting start defaults to 0.
 Omitting end goes up to the string length.
 The step parameter can skip characters.
 Negative indices allow slicing from the end.
 A slice never raises an error if out of range.
 Strings can be reversed with [::-1].
 Slicing does not change the original string.
 Widely used in substring operations.

Example (Indented)

s = "Python"
print(s[0:4]) # Pyth
3

print(s[::-1]) # nohtyP

1.6 String Comparison

 Strings can be compared using relational operators (==, !=, <, >).
 Comparison is based on lexicographic (dictionary) order.
 It is case-sensitive.
 Unicode values decide order (ord() function shows value).
 == checks for exact equality.
 Useful for sorting and searching.
 Comparisons can involve substrings.
 Lowercase letters are considered greater than uppercase.
 Use .lower() for case-insensitive comparison.
 Important in authentication and validations.

Example (Indented)

print("apple" < "banana") # True


print("Apple" < "apple") # True

1.7 Strings are Immutable

 Once created, strings cannot be changed.


 Indexing cannot assign a new value.
 Any modification creates a new string.
 Example: replacing first letter requires concatenation.
 Tuples are also immutable, but lists are mutable.
 Immutability ensures data safety.
 Saves memory by reusing string objects.
 A string variable can be reassigned to a new string.
 Common error: trying to update characters directly.
 Applications: security, hashing, dictionary keys.

Example (Indented)

s = "Hello"
s = "Y" + s[1:]
print(s) # Yello

1.8 The in and not in Operators

 in checks if a substring exists in a string.


 not in checks if a substring is absent.
 Returns a Boolean (True or False).
 Case-sensitive by default.
 Works with single characters and substrings.
 Often used in conditions and loops.
 Simplifies searching operations.
 Works faster than manual traversal.
4

 Useful for validation and filtering.


 Essential in text analysis and searching.

Example (Indented)

s = "Python"
print("Py" in s) # True
print("Java" not in s) # True

1.9 A Find Function

 Custom function can be written to locate a character.


 Traverses string using a loop.
 Returns the index of the first match.
 Returns -1 if not found.
 Works for single characters.
 Can be extended for substrings.
 Demonstrates traversal logic.
 Safer than assuming index exists.
 Highlights immutability of strings.
 Good practice for learning string operations.

Example (Indented)

def find(str, ch):


for i in range(len(str)):
if str[i] == ch:
return i
return -1

print(find("Python","t")) # 2

1.10 Looping and Counting

 Loops can be used to count occurrences.


 A counter variable is updated when matches are found.
 Works for characters or substrings.
 Case-sensitive by default.
 Can be modified for case-insensitive search.
 Python provides built-in .count() as shortcut.
 Looping is more flexible for conditions.
 Useful in text frequency analysis.
 Common mistake: wrong loop variable.
 Important in data analytics and NLP.

Example (Indented)

s = "banana"
count = 0
for ch in s:
if ch == "a":
count += 1
5

print(count) # 3

1.11 Optional Parameters

 Many string methods accept start and end arguments.


 Restrict operation to part of the string.
 Default start is 0.
 Default end is length of string.
 Used in find(), count(), etc.
 Helps in repeated searches.
 Prevents scanning the whole string.
 End index is exclusive.
 Provides efficiency in long strings.
 Common mistake: misunderstanding end index.

Example (Indented)

s = "banana"
print([Link]("a", 2)) # 3
print([Link]("a", 2, 5)) # 2

1.12 The Built-in Find Method

 find() returns the index of the first occurrence.


 Returns -1 if substring is not found.
 Accepts optional start and end.
 Case-sensitive search.
 Safer than index() (which raises an error).
 rfind() searches from the right.
 Works with substrings of any length.
 Useful in parsing and validation.
 Important in substring search.
 Common mistake: confusing with index().

Example (Indented)

s = "banana"
print([Link]("na")) # 2
print([Link]("na", 3)) # 4

1.13 The Split Method

 Splits a string into a list of substrings.


 Default delimiter is whitespace.
 Custom delimiter can be specified.
 Consecutive delimiters may give empty strings.
 Can limit the number of splits.
 Useful for tokenization of text.
 Works well with CSV-style data.
6

 rsplit() splits from the right.


 Result is always a list.
 Common mistake: forgetting correct delimiter.

Example (Indented)

s = "apple,banana,cherry"
print([Link](",")) # ['apple','banana','cherry']

1.14 Cleaning Up Your Strings

 Strings may contain unwanted spaces.


 strip() removes spaces from both ends.
 lstrip() removes from left only.
 rstrip() removes from right only.
 Can remove custom characters too.
 replace() removes or replaces substrings.
 .lower() and .upper() normalize text.
 Regular expressions allow advanced cleaning.
 Important in user input handling.
 Useful in text preprocessing.

Example (Indented)

s = " hello "


print([Link]()) # "hello"

1.15 The String Format Method

 Used to insert values into strings.


 Placeholders {} are replaced with values.
 Index numbers can control positions.
 Named placeholders are also supported.
 Supports number formatting.
 f-strings are modern alternative (Python 3.6+).
 Allows alignment and padding.
 Useful for dynamic text creation.
 Common mistake: mismatch in arguments.
 Essential in report generation and output formatting.

Example (Indented)

name = "Alice"
age = 21
print("My name is {} and I am {} years old".format(name, age))
7

CHAPTER 2: TUPLES

2.1 Tuples are Used for Grouping Data

 A tuple is an ordered collection of elements enclosed in parentheses ( ).


 Tuples can store multiple data types (integers, strings, floats, booleans, lists, other
tuples).
 Tuples can have duplicate values.
 Empty tuples can be created using ().
 A tuple with a single element must have a trailing comma (5,).
 Tuples are immutable (cannot be changed once created).
 Tuples are faster than lists because of immutability.
 Tuples can be used as dictionary keys (unlike lists).
 Tuples are useful when fixed data is required.
 Common applications: coordinates, RGB values, fixed records.

Example (Indented)

t1 = (1, 2, 3)
t2 = ("Alice", 21, True, 3.14)
print(t1)
print(t2)

2.2 Tuple Assignment

 Tuple assignment allows assigning multiple variables at once.


 Variables are assigned values based on position.
 Useful for unpacking tuples easily.
 Supports simultaneous variable swaps.
 Can ignore values using _ as placeholder.
 Nested unpacking is possible.
 Error occurs if variable count ≠ tuple size.
 Useful in returning multiple values.
 Makes code shorter and cleaner.
 Helps in iterable unpacking during loops.

Example (Indented)

(a, b, c) = (10, 20, 30)


print(a, b, c) # 10 20 30

x, y = 5, 7
x, y = y, x
print(x, y) # 7 5

2.3 Tuples as Return Values

 Functions can return multiple values using tuples.


 Returned values are packed inside a tuple.
 Caller can unpack values into separate variables.
8

 Avoids the need for multiple return statements.


 Tuples make code cleaner and structured.
 Useful when different data types must be returned.
 Common in functions like division (quotient, remainder).
 Parentheses are optional when returning tuples.
 Helps organize grouped results in one object.
 Widely used in real-world applications like database records.

Example (Indented)

def divide(a, b):


q = a // b
r = a % b
return (q, r)

quot, rem = divide(17, 5)


print("Quotient:", quot, "Remainder:", rem)

2.4 Composability of Data Structures

 Tuples can contain other tuples (nested tuples).


 Tuples can be stored inside lists.
 Lists can also be stored inside tuples.
 Tuples can be used as dictionary keys.
 Nested tuples can represent structured data like matrices.
 Composability allows creating complex hierarchical structures.
 Tuples combined with sets or dictionaries create powerful data models.
 Immutability ensures data integrity inside composite structures.
 Example: storing student data (id, (name, age, branch)).
 Applications: graphs, records, hierarchical datasets.

Example (Indented)

t = ((1, 2), (3, 4))


print(t[0][1]) # 2

students = [("John", 21), ("Sara", 20)]


print(students[0][0]) # John
9

CHAPTER 3: LISTS

3.1 List Values

 A list is an ordered, mutable collection enclosed in square brackets [ ].


 Lists can store multiple data types (integers, strings, floats, booleans, lists, tuples).
 Lists allow duplicate values.
 Lists can be empty ([]).
 Lists can contain nested lists.
 Lists are dynamic and can grow or shrink.
 Lists are widely used to represent collections.
 Lists are indexed and can be traversed.
 Lists can represent structured data like matrices.
 Applications: storing student records, datasets, sequences.

Example (Indented)

nums = [1, 2, 3, 4]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hi", 3.14, True]
print(nums)
print(fruits)
print(mixed)

3.2 Accessing Elements

 Elements are accessed using indices inside square brackets.


 The first element has index 0.
 Negative indices access elements from the end.
 Nested lists require double indexing.
 Accessing out of range raises IndexError.
 Lists can be accessed inside loops.
 Indexing allows reading or updating values.
 Direct iteration through elements is possible.
 Indexing works for both single and nested lists.
 Essential for extracting and modifying elements.

Example (Indented)

fruits = ["apple", "banana", "cherry"]


print(fruits[0]) # apple
print(fruits[-1]) # cherry

matrix = [[1,2],[3,4]]
print(matrix[1][0]) # 3

3.3 List Length

 The len() function gives the number of elements in a list.


 Length includes duplicates.
10

 Works on both simple and nested lists.


 Empty lists have length 0.
 Useful in iteration and validation.
 Helps in loops to control indexing.
 Changes dynamically as list grows or shrinks.
 Does not require manual counting.
 Common mistake: using [Link]() (incorrect).
 Applications: validation, traversal, algorithms.

Example (Indented)

nums = [10, 20, 30]


print(len(nums)) # 3

3.4 List Membership

 Membership is checked using in and not in.


 Returns True if element exists.
 Returns False if not present.
 Works with numbers, strings, and nested lists.
 Case-sensitive for strings.
 Simplifies searching tasks.
 Can be used inside conditions.
 Works in both small and large lists.
 Returns Boolean values only.
 Useful in filtering, searching, and validation.

Example (Indented)

fruits = ["apple", "banana", "cherry"]


print("apple" in fruits) # True
print("mango" not in fruits) # True

3.5 List Operations

 Lists support concatenation using +.


 Lists support repetition using *.
 Lists can be compared using relational operators.
 Membership operations can be applied.
 Lists can be indexed and sliced.
 Iteration works on lists.
 Lists can be combined with other sequences.
 Operations allow manipulation and extension.
 Useful for merging or repeating sequences.
 Applications: dataset handling, pattern creation.

Example (Indented)

a = [1, 2]
b = [3, 4]
11

print(a + b) # [1,2,3,4]
print(a * 3) # [1,2,1,2,1,2]

3.6 List Slices

 Slices extract part of a list.


 Syntax: list[start:end:step].
 Start defaults to 0 if omitted.
 End defaults to list length if omitted.
 Step can be positive or negative.
 Negative step reverses the list.
 Slices do not cause IndexError if out of range.
 Lists can be reversed with slicing.
 Original list is not modified.
 Applications: sublists, reversing, sampling.

Example (Indented)

nums = [10, 20, 30, 40, 50]


print(nums[1:4]) # [20,30,40]
print(nums[::-1]) # [50,40,30,20,10]

3.7 Lists are Mutable

 List elements can be changed after creation.


 Indexing allows reassignment of elements.
 New values can replace old ones.
 Lists can grow with append and extend.
 Lists can shrink with remove or pop.
 Mutability makes lists flexible.
 Mutability can cause unintended side effects.
 Lists differ from tuples (tuples are immutable).
 Lists allow direct updates unlike strings.
 Applications: dynamic data storage and manipulation.

Example (Indented)

fruits = ["apple", "banana"]


fruits[1] = "orange"
print(fruits) # ['apple','orange']

3.8 List Deletion

 Elements can be deleted using del.


 remove() deletes the first matching element.
 pop() deletes by index and returns the element.
 clear() removes all elements.
 Deletion reduces list length.
 Errors occur when deleting non-existent elements.
12

 Useful in memory management.


 Helps maintain clean data.
 Allows selective removal of data.
 Important in dynamic applications.

Example (Indented)

nums = [1,2,3,4]
del nums[1] # [1,3,4]
[Link](3) # [1,4]
[Link]() # [1]

3.9 Objects and References

 Lists are stored as objects in memory.


 Variables store references to these objects.
 Assigning a list to another variable creates an alias.
 Both variables point to the same memory location.
 Modifying one affects the other.
 Use id() to check memory address.
 Aliasing saves memory but can cause bugs.
 Useful for shared updates.
 Problematic in large programs with references.
 Applications: efficient memory usage.

Example (Indented)

a = [1,2,3]
b = a
b[0] = 99
print(a) # [99,2,3]

3.10 Aliasing

 Aliasing occurs when two variables refer to the same list.


 Both variables point to the same memory location.
 Modifying one variable’s list changes the other as well.
 Use is to check if two variables point to the same list.
 == checks for equality of values, not memory location.
 Aliasing is common when passing lists to functions.
 It can lead to unexpected side effects.
 Saves memory by avoiding duplication.
 Problematic in large programs with shared data.
 Applications: efficient memory use, but requires careful handling.

Example (Indented)

x = [10, 20, 30]


y = x
[Link](40)
13

print(x) # [10,20,30,40]
print(x is y) # True

3.11 Cloning Lists

 Cloning creates a new list that is a copy of an existing list.


 Prevents aliasing problems.
 Method 1: Slicing ([:]).
 Method 2: list() constructor.
 Method 3: .copy() method.
 For nested lists, use [Link]() for deep copy.
 Cloned lists have different memory locations.
 Modifying one does not affect the other.
 Shallow copy copies only top-level elements.
 Applications: safe backups of lists for independent use.

Example (Indented)

a = [1,2,3]
b = a[:] # clone using slicing
a[0] = 99
print(a) # [99,2,3]
print(b) # [1,2,3]

3.12 Lists and for Loops

 Lists can be traversed using for loops.


 Direct iteration prints elements one by one.
 Index-based iteration uses range(len(list)).
 enumerate() provides index and value together.
 Nested loops handle nested lists or matrices.
 Lists can be traversed forwards or backwards.
 reversed() can be used for reverse traversal.
 Traversal allows searching, filtering, and processing.
 Modifying a list while iterating can cause errors.
 Applications: algorithms, searching, data processing.

Example (Indented)

nums = [10,20,30]
for i, val in enumerate(nums):
print(i, val)

3.13 List Parameters

 Lists can be passed as arguments to functions.


 Lists are passed by reference, not by value.
 Function modifications affect the original list.
 To avoid, clone the list inside the function.
14

 Functions can return lists.


 Lists as parameters allow flexible data handling.
 Useful in modular programming.
 Large datasets can be processed efficiently.
 Allows in-place modification when required.
 Applications: sorting, filtering, and algorithms.

Example (Indented)

def add(lst, val):


[Link](val)

nums = [1,2]
add(nums, 3)
print(nums) # [1,2,3]

3.14 List Methods

 append(x) → adds an element to the end.


 extend([x,y]) → adds multiple elements.
 insert(i, x) → inserts at a position.
 remove(x) → removes first occurrence of value.
 pop(i) → removes and returns element at index.
 index(x) → returns index of first occurrence.
 count(x) → counts occurrences of element.
 sort() → sorts list in ascending order.
 reverse() → reverses list order.
 clear() → removes all elements.

Example (Indented)

nums = [3,1,2,3]
[Link](4)
[Link]()
print(nums) # [1,2,3,3,4]
print([Link](3)) # 2

3.15 Pure Functions and Modifiers

 Pure functions do not modify the original list.


 They return a new list with changes.
 Example: sorted() creates a new sorted list.
 Modifiers change the original list in place.
 Example: [Link]() modifies the list directly.
 Pure functions are safer, avoiding side effects.
 Modifiers are faster but riskier.
 Both types are useful depending on context.
 Pure functions are common in functional programming.
 Applications: choosing between safety and performance.
15

Example (Indented)

a = [3,1,2]
b = sorted(a) # pure function
[Link]() # modifier

3.16 Functions that Produce Lists

 Functions can return new lists.


 Useful for generating sequences.
 Can return filtered lists.
 Can produce computed lists (like squares).
 Can merge multiple lists.
 Can create nested lists (like matrices).
 List comprehensions are often used.
 Improves code reusability.
 Functions avoid duplication of logic.
 Applications: dataset creation, simulations.

Example (Indented)

def squares(n):
return [i*i for i in range(n)]

print(squares(5)) # [0,1,4,9,16]

3.17 Strings and Lists

 Strings can be converted to lists.


 list("hello") → ['h','e','l','l','o'].
 split() splits string into list of words.
 join() combines list into string.
 Strings are immutable, lists are mutable.
 Converting strings to lists allows easier manipulation.
 Useful in reversing or modifying characters.
 Error: join() requires all elements to be strings.
 Often used in text processing.
 Applications: cleaning, parsing, NLP tasks.

Example (Indented)

s = "a b c"
lst = [Link]()
print(lst) # ['a','b','c']
print("-".join(lst)) # a-b-c

3.18 List and Range


16

 range(n) generates numbers from 0 to n-1.

 list(range(n)) creates a list from range.


 Custom ranges can start from any number.
 Step parameter allows skipping values.
 Negative step reverses the sequence.
 Useful for loops and iterations.
 Memory efficient compared to large lists.
 End value is exclusive.
 Can be converted into lists easily.
 Applications: sequence generation, iteration.

Example (Indented)

print(list(range(5))) # [0,1,2,3,4]
print(list(range(10,0,-2))) # [10,8,6,4,2]

3.19 Nested Lists

 Lists can contain other lists.


 Used to represent multi-dimensional data.
 Access requires multiple indices.
 Can represent tables or matrices.
 Useful in hierarchical data storage.
 Nested lists can be modified.
 Traversed using nested loops.
 Shallow copies cause reference issues.
 Deep copies avoid shared references.
 Applications: 2D arrays, graphs, trees.

Example (Indented)

matrix = [[1,2],[3,4]]
print(matrix[0][1]) # 2

3.20 Matrices (Lists of Lists)

 Python does not have a built-in matrix type.


 Lists of lists are used as matrices.
 Each inner list represents a row.
 Elements are accessed by [row][column].
 Matrices can be modified element-wise.
 Nested loops allow full traversal.
 Zero matrices can be created using list comprehension.
 Pitfall: using multiplication ([[0]*3]*3) causes aliasing.
17

 Applications: image processing, numerical computing.


 Libraries like NumPy provide advanced matrix operations.

Example (Indented)

matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix[1][2]) # 6

zeros = [[0]*3 for _ in range(3)]


print(zeros)

You might also like