13 BSC CS Python CHP 4
13 BSC CS Python CHP 4
E
You can create a string by assigning a print(result) # Output: Hello,
sequence of characters to a variable using
EG
World!
either single or double quotes.
Multi-line strings can be created using triple Example 5: Repeating Strings You can also
LL
quotes. repeat a string multiple times using the *
operator.
O
Syntax:
C
repeat_str = "Hello " * 3
# Using single quotes print(repeat_str) # Output:
str1 = 'Hello, World!'
EE
Hello Hello Hello
# Using double quotes
Functions of Strings in Python
R
Examples
text = "hello world"
print(text.capitalize()) # Example 1: Using len(), upper(), and
E
Output: Hello world lower()
EG
str.title() - Capitalizes the first
character of each word. message = "Hello, World!"
print(len(message)) #
LL
Output: 13
text = "hello world"
print(message.upper()) #
print(text.title()) # Output:
O
Output: HELLO, WORLD!
Hello World
print(message.lower()) #
C
str.strip() - Removes any leading and Output: hello, world!
trailing whitespace from the string.
EE
Example 2: Stripping Whitespace and
text = " Hello, World! " Replacing Substrings
R
print(text.strip()) # Output:
EG
substring. print(cleaned_text) #
Output: Welcome to Python
.M
2
words = ["Data", "Science", name = "Alice"
"is", "amazing"] age = 25
sentence = " ".join(words) print(f"My name is {name} and I
print(sentence) # am {age} years old.")
Output: Data Science is amazing
Checking String Content
Example 5: Using title() and
capitalize() ○str.isdigit() checks if all characters
are digits.
○str.isalpha() checks if all characters
text = "hello world" are alphabetic.
print(text.title()) # ○str.isalnum() checks if characters are
E
Output: Hello World alphanumeric.
EG
print(text.capitalize()) #
Output: Hello world text = "Python3"
print(text.isalpha()) # Output:
LL
Working with Strings in Python False
print(text.isalnum()) # Output:
Manipulating Strings
O
True
C
Python strings come with many methods to
perform various operations, such as searching, Searching for Substrings
replacing, and modifying text.
EE
○str.find() returns the index of the
By working with strings, you can handle user first occurrence of the substring (or -1 if
R
substring.
Common String Manipulation Techniques ○str.startswith() /
str.endswith() checks if the string
.D
Concatenation
starts/ends with a specific substring.
Combines multiple strings into a single string
using the + operator.
.M
first = "Hello"
# Output: 7
second = "World"
print(message.count("o"))
IG
# Output: True
Repetition
SH
Modifying Case
Repeats a string multiple times using the *
Methods like str.upper(),
operator.
str.lower(), str.capitalize(), and
str.title() change the case of characters.
word = "Hi! "
print(word * 3) # Output: Hi!
sentence = "learning python"
Hi! Hi!
print(sentence.capitalize()) #
String Formatting Output: Learning python
Uses placeholders to format and insert
variables into a string, which can be done with
f-strings, format(), or %. Splitting and Joining Strings
3
○str.split(delimiter) splits a # Output: 12
string into a list based on the given print(sentence.count("in"))
delimiter.
# Output: 3
○str.join(iterable) joins a list
into a string with elements separated by a
specified delimiter. Example 5: Splitting and Joining
E
print(" | ".join(word_list)) # 'bananas']
Output: Python | is | easy | to new_text = " and
EG
| learn ".join(fruit_list)
print(new_text)
LL
Examples of Working with Strings # Output: apples and oranges and
bananas
Example 1: Concatenation and Repetition
O
Finding the Number of Characters and
C
greeting = "Good " + "Morning" Words in a String
repeat_greeting = greeting * 2 Counting Characters Use the len()
EE
print(greeting) # function to find the number of characters in a
Output: Good Morning string, including spaces.
R
print(repeat_greeting) #
Output: Good MorningGood Morning text = "Python programming"
EG
print(len(text)) # Output: 18
(counts spaces as well)
Example 2: Formatting with f-strings
.D
print(word_count) # Output: 4
Alphabets
SH
E
this sentence."
EG
word_count = Syntax and Example:
len(sentence.split()) # Creating a list
print(f"Number of words: fruits = ["apple", "banana",
LL
{word_count}") # Output: Number "cherry"]
of words: 6 numbers = [1, 2, 3, 4, 5]
O
mixed_list = ["text", 10, 5.5,
C
Example 3: Inserting a Substring at a Specific True]
Index
EE
print(fruits) # Output:
text = "Hello World" ['apple', 'banana', 'cherry']
# Inserting " Python" at index 5 print(numbers) # Output: [1,
R
5
insert() - Inserts an element at a specified ['apple', 'banana', 'cherry']
index.
List Operations
fruits.insert(1, "kiwi")
Concatenation (+) - Combines two lists.
print(fruits) # Output:
['apple', 'kiwi', 'banana',
'cherry'] list1 = [1, 2, 3]
list2 = [4, 5, 6]
remove() - Removes the first occurrence of the combined = list1 + list2
specified element.
print(combined) # Output: [1,
2, 3, 4, 5, 6]
fruits.remove("banana")
Repetition (*) - Repeats the list a specified
E
print(fruits) # Output:
number of times.
['apple', 'cherry']
EG
pop() - Removes and returns the element at the repeated = list1 * 3
specified index (default is the last item).
print(repeated) # Output: [1,
LL
2, 3, 1, 2, 3, 1, 2, 3]
fruits.pop(2)
Membership (in) - Checks if an element
O
print(fruits) # Output:
exists in the list.
['apple', 'banana']
C
index() - Returns the index of the first print(3 in list1) # Output:
EE
occurrence of the specified element.
True
print(10 in list1) # Output:
print(fruits.index("cherry")) #
R
False
Output: 2
EG
# Output:
sort() - Sorts the list in ascending order. # apple
.P
# banana
numbers = [4, 2, 9, 1] # cherry
IG
numbers.sort()
print(numbers) # Output: [1, 2, Examples of List Operations
R
4, 9]
Example 1: Adding and Removing Elements
SH
6
colors.insert(1, "purple") ● step - The interval between elements
(optional).
print(colors) # Output: ['red',
'purple', 'blue', 'yellow'] Example:
E
print(numbers) # Output: [7, 4, print(numbers[::-1]) #
2, 1] Output: [6, 5, 4, 3, 2, 1, 0]
EG
Nested Lists
LL
Example 4: Copying and Counting Elements
A nested list is a list that contains other lists as
new_colors = colors.copy() its elements.
O
print(new_colors.count("red")) Example:
C
# Output: 1
EE
matrix = [
Example 5: List Concatenation and Repetition [1, 2, 3],
[4, 5, 6],
R
4, 6, 1, 3, 5] list
print(odd * 2) # Output: [1, print(matrix[1][2]) # Output: 6
.M
List slicing allows you to access a specific A tuple is an immutable, ordered collection in
portion (or "slice") of a list by specifying a Python, which means elements cannot be
range of indices. added, removed, or changed after creation.
R
This feature helps extract sublists, create Tuples are typically used for data that should
SH
copies, and perform various operations on not be modified, like constant values or fixed
portions of lists without affecting the original data records.
list.
Syntax:
Syntax:
# Creating a tuple
list[start:end:step] coordinates = (10, 20)
7
colors = ("red", "green", [7, 8, 9]
"blue") ]
numbers = 1, 2, 3 print(matrix[2][1]) # Output: 8
print(colors) # Output:
('red', 'green', 'blue') Example 3: Creating and Using Tuples
print(numbers) # Output: (1,
2, 3) # Defining a tuple and using it
dimensions = (10, 20, 30)
print("Length:", dimensions[0])
4. Functions in Tuples # Output: Length: 10
E
provides various functions to work with them
Example 4: Counting Elements in a Tuple
EG
effectively.
LL
occurrences
fruits = ("apple", "banana",
colors = ("red", "green", "apple", "orange", "apple")
O
"blue") print(fruits.count("apple")) #
C
print(len(colors)) # Output: 3 Output: 3
index() - Returns the index of the first
EE
occurrence of the specified element. Example 5: Tuple with Mixed Data Types
R
print(student_info) # Output:
('John', 21, 'Computer Science')
numbers = (1, 2, 2, 3, 4, 2)
.M
print(numbers.count(2)) #
Output: 3 Dictionaries in Python
.P
"C++", "JavaScript"]
specific identifier (key).
print(languages[1:3]) # Output:
['Java', 'C++'] Syntax:
E
Dictionaries can also be created using the Dictionary Methods
EG
dict() constructor:
Dictionaries come with several useful methods
for adding, modifying, and retrieving
LL
student = dict(name="Alice", key-value pairs.
age=20, course="Computer
Science") Common Dictionary Methods:
O
print(student)
get() - Returns the value associated with a
C
# Output: {'name': 'Alice',
specified key. If the key does not exist, it
'age': 20, 'course': 'Computer
returns a default value (usually None).
EE
Science'}
R
○in - Checks if a specified key exists in keys() - Returns a list of all keys in the
.M
print(student.keys()) # Output:
student = {"name": "Alice", dict_keys(['name', 'grade'])
"age": 20}
values() - Returns a list of all values in the
R
Output: True
print("grade" not in student) #
print(student.values()) #
Output: True
Output: dict_values(['Alice',
'A'])
Assignment Operator (=)
items() - Returns a list of all key-value
○Used to add or update key-value pairs in pairs as tuples.
the dictionary.
print(student.items()) #
student["grade"] = "A" Output: dict_items([('name',
print(student) 'Alice'), ('grade', 'A')])
# Output: {'name': 'Alice',
9
update() - Updates the dictionary with Example 3: Using get() with Default
another dictionary or a set of key-value pairs. Values
E
returns its value.
# Output:
EG
# name : Bob
grade = student.pop("grade")
# age : 23
print(grade) # Output: A
# major : Physics
LL
print(student) # Output:
{'name': 'Alice', 'age': 21,
Example 5: Using update() with New Data
O
'major': 'Math'}
clear() - Removes all items from the
C
student.update({"age": 24,
dictionary.
"grade": "A"})
EE
print(student) # Output:
student.clear() {'name': 'Bob', 'age': 24,
print(student) # Output: {}
R
Example 1: Accessing Values and Checking Using for Loop with Dictionaries
.D
for Keys
Types of Iteration in Dictionaries:
.M
Output: False
print(key)
SH
E
student.items():
EG
print(key, ":", value) 4. Clearing All Items
# Output:
# name : Alice The .clear() method removes all items
LL
# age : 20 from the dictionary, leaving it empty.
# course : CS
O
student.clear()
print(student)
C
Operations on Dictionaries
# Output: {}
1. Adding or Updating Items
EE
5. Copying a Dictionary
To add or update an item, assign a value to a
specific key. If the key already exists, the
R
pair is added.
student_copy = student.copy()
student["age"] = 21 #
.D
print(student_copy)
Updating an existing key
# Output: {'name': 'Alice',
student["grade"] = "A" #
'age': 21, 'grade': 'A',
.M
# Dictionary example
11
product = {"name": "Laptop", Example 4: Clearing and Copying a
Dictionary
"price": 700, "brand": "Dell"}
data = {"name": "Alice", "age":
# Looping through keys
21}
for key in product:
data_copy = data.copy() #
print("Key:", key)
Creating a copy
data.clear() #
# Looping through values
Clearing the original dictionary
for value in product.values():
print(data) #
print("Value:", value)
Output: {}
print(data_copy) #
# Looping through key-value
E
Output: {'name': 'Alice', 'age':
pairs
EG
21}
for key, value in
product.items():
LL
print(f"{key} -> {value}")
Example 5: Using get() to Access Values
Safely
O
Example 2: Adding, Updating, and Deleting
user = {"username": "jdoe",
C
Items
"email": "jdoe@example.com"}
EE
inventory = {"apples": 10, print(user.get("username"))
"oranges": 15, "bananas": 5} # Output: jdoe
inventory["grapes"] = 8 print(user.get("phone", "N/A"))
R
# Removing an item
print(inventory)
.M
25}
dict2 = {"city": "New York",
"age": 26} # Existing key in
dict1 will be overwritten
dict1.update(dict2)
# Merging dict2 into dict1
print(dict1)
# Output: {'name': 'Alice',
'age': 26, 'city': 'New York'}
12