Python Fundamentals – Level 3: String Methods, Function Arguments, Lists & Dictionaries

Python Fundamentals – Level 3: String Methods, Function Arguments, Lists & Dictionaries

Python for Cybersecurity Tutorial Series

Welcome to Level 3 of the Python Fundamentals series!

In Level 1, we covered Python basics, including strings, variables, data types, operators, conditional statements, and loops.

In Level 2, we explored functions, modules, libraries, objects, methods, and attributes.

Now, we'll build on that knowledge by learning how to manipulate strings, pass different types of arguments to functions, and work with two essential Python data structures: lists and dictionaries.

These concepts are particularly important when working with large amounts of data, processing information, automating tasks, and developing cybersecurity tools.


1. Common String Methods

Python provides several built-in string methods that allow us to manipulate and examine text.

A string method is a function associated with the string object. We call it using dot notation.

Let's start with a simple example:

message = "hello python"

print(message.upper())

Output:

HELLO PYTHON

The upper() method converts all characters in a string to uppercase.

1.1 Common String Methods

MethodDescription
upper()Converts all characters to uppercase.
lower()Converts all characters to lowercase.
capitalize()Capitalizes the first character.
title()Capitalizes the first character of each word.
strip()Removes leading and trailing whitespace.
replace()Replaces a specified substring with another.
split()Splits a string into a list.
find()Returns the position of a substring, or -1 if not found.
count()Counts occurrences of a substring.
startswith()Checks whether a string starts with a specified value.
endswith()Checks whether a string ends with a specified value.

1.2 Changing Letter Cases

text = "python programming"

print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())

Output:

PYTHON PROGRAMMING
python programming
Python programming
Python Programming

1.3 Removing Whitespace

The strip() method removes whitespace from the beginning and end of a string.

username = "   Roger   "

print(username.strip())

Output:

Roger

You can also use:

  • lstrip() – Removes whitespace from the left.

  • rstrip() – Removes whitespace from the right.

1.4 Replacing Text

The replace() method replaces one substring with another.

message = "I like Java"

updated_message = message.replace("Java", "Python")

print(updated_message)

Output:

I like Python

1.5 Splitting Strings

The split() method divides a string into a list of smaller strings.

By default, it splits the string wherever whitespace occurs.

message = "Python is useful for cybersecurity"

words = message.split()

print(words)

Output:

['Python', 'is', 'useful', 'for', 'cybersecurity']

You can also specify a separator.

ip_address = "192.168.1.10"

parts = ip_address.split(".")

print(parts)

Output:

['192', '168', '1', '10']

This can be useful when processing structured text, IP addresses, and log entries.

1.6 Finding and Counting Characters

The find() method returns the index of the first occurrence of a substring.

message = "Python programming"

print(message.find("programming"))

Output:

7

Remember that string indexing starts at zero.

The count() method counts how many times a substring appears.

message = "banana"

print(message.count("a"))

Output:

3

1.7 Checking the Beginning and End of Strings

The startswith() and endswith() methods return Boolean values.

website = "www.example.com"

print(website.startswith("www"))
print(website.endswith(".com"))

Output:

True
True

1.8 String Immutability

An important property of Python strings is that they are immutable.

This means that you cannot directly modify an existing string character by character.

Instead, string methods return a new string.

text = "hello"

text.upper()

print(text)

Output:

hello

The original variable remains unchanged.

To store the modified string, assign the result back to the variable:

text = "hello"

text = text.upper()

print(text)

Output:

HELLO

2. Parameter Types in Python

When defining functions, Python allows us to work with different types of parameters.

Parameters determine how information can be passed into a function.

There are several parameter types to understand:

  1. Positional-or-keyword parameters.

  2. Variable-length positional parameters (*args).

  3. Variable-length keyword parameters (**kwargs).

2.1 Positional-or-Keyword Parameters

Positional-or-keyword parameters are the default parameter type in Python.

They can receive arguments through their position or by explicitly specifying their parameter names.

Consider the following function:

def greet(message, name="Alice"):
    print(message, name)

We can call this function using positional arguments:

greet("Hello", "Roger")

Output:

Hello Roger

We can also use keyword arguments:

greet(message="Hello", name="Ana")

Output:

Hello Ana

Notice that name has a default value of "Alice".

This means that we can omit it when calling the function:

greet("Welcome")

Output:

Welcome Alice

Important: Positional-or-keyword describes how a parameter can receive an argument. A default value is a separate feature that makes an argument optional.

2.2 Variable-Length Positional Parameters (*args)

Sometimes, we don't know how many positional arguments will be passed to a function.

Python provides *args to handle this situation.

The *args parameter collects additional positional arguments into a tuple.

Example:

def func(foo, *args):
    print(foo)
    print(args)

func(10, 20, 30, 40)

Output:

10
(20, 30, 40)

Let's break this down:

  • foo receives the first argument, 10.

  • *args collects the remaining arguments.

  • The collected arguments are stored inside a tuple.

You can also loop through the arguments:

def display_tools(*args):

    for tool in args:
        print(tool)

display_tools("Nmap", "Wireshark", "Burp Suite")

Output:

Nmap
Wireshark
Burp Suite

The name args is a convention. You can use another name, but the asterisk (*) is what makes it collect extra positional arguments.

2.3 Variable-Length Keyword Parameters (**kwargs)

Python also allows functions to accept an arbitrary number of keyword arguments.

We use **kwargs for this purpose.

Unlike *args, which collects positional arguments into a tuple, **kwargs collects keyword arguments into a dictionary.

Example:

def func(foo, **kwargs):
    print(foo)
    print(kwargs)

func(
    "Laptop",
    brand="Apple",
    price=1200,
    color="Silver"
)

Output:

Laptop
{'brand': 'Apple', 'price': 1200, 'color': 'Silver'}

Let's understand the result:

  • foo receives "Laptop".

  • **kwargs collects the remaining keyword arguments.

  • Each keyword becomes a dictionary key, and its value is stored alongside it.

You can access the collected values like a normal dictionary:

def display_product(name, **kwargs):

    print("Product:", name)

    for key, value in kwargs.items():
        print(key, ":", value)

display_product(
    "Laptop",
    brand="Apple",
    price=1200,
    color="Silver"
)

Output:

Product: Laptop
brand : Apple
price : 1200
color : Silver

2.4 Using *args and **kwargs Together

We can combine different parameter types in the same function.

def example(foo, *args, **kwargs):
    print("First argument:", foo)
    print("Extra positional arguments:", args)
    print("Extra keyword arguments:", kwargs)

example(10, 20, 30, name="Roger", age=26)

Output:

First argument: 10
Extra positional arguments: (20, 30)
Extra keyword arguments: {'name': 'Roger', 'age': 26}

This approach is useful when creating flexible functions that accept different numbers of arguments.


3. Lists

A list is an ordered collection of values.

Lists allow us to store multiple items inside a single variable.

A list is written using square brackets [], with individual elements separated by commas.

Example:

tools = ["Nmap", "Wireshark", "Burp Suite"]

print(tools)

Output:

['Nmap', 'Wireshark', 'Burp Suite']

A list can contain different data types:

information = ["Roger", 26, 181.5, True]

print(information)

Output:

['Roger', 26, 181.5, True]

Lists are mutable, which means that we can add, remove, or modify their elements after creation.

3.1 Accessing List Elements

Each element in a list has an index number.

Python uses zero-based indexing, meaning that the first element has an index of 0.

tools = ["Nmap", "Wireshark", "Burp Suite"]

print(tools[0])
print(tools[1])
print(tools[2])

Output:

Nmap
Wireshark
Burp Suite

You can also use negative indexes to access elements from the end of a list.

tools = ["Nmap", "Wireshark", "Burp Suite"]

print(tools[-1])
print(tools[-2])

Output:

Burp Suite
Wireshark

3.2 Index Out of Range

Trying to access an index that does not exist will raise an IndexError exception.

tools = ["Nmap", "Wireshark"]

print(tools[5])

Output:

IndexError: list index out of range

The list only contains indexes 0 and 1.

3.3 Modifying List Elements

Since lists are mutable, we can change individual elements by assigning a new value to their index.

tools = ["Nmap", "Wireshark", "Burp Suite"]

tools[1] = "Metasploit"

print(tools)

Output:

['Nmap', 'Metasploit', 'Burp Suite']

3.4 List Slicing

List slicing allows us to retrieve a specific portion of a list.

The general syntax is:

list_name[start:stop:step]

Example:

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4])

Output:

[20, 30, 40]

The starting index is included, but the ending index is excluded.

You can also omit some of the values:

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[:3])
print(numbers[3:])
print(numbers[::2])

Output:

[10, 20, 30]
[40, 50, 60]
[10, 30, 50]

4. List Filtering Elements

Python provides a convenient feature called list comprehension.

List comprehension allows us to create a new list based on an existing iterable, optionally applying a condition to select specific elements.

Instead of writing a traditional loop, we can perform the operation in a single expression.

4.1 Basic List Comprehension

numbers = [1, 2, 3, 4, 5]

squares = [x * x for x in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

Here, Python takes each element from numbers, multiplies it by itself, and stores the result in a new list.

4.2 Filtering with an IF Condition

We can add an if condition to select only specific elements.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = [x for x in numbers if x % 2 == 0]

print(even_numbers)

Output:

[2, 4, 6, 8, 10]

The expression x % 2 == 0 checks whether a number is even.

Only elements that satisfy this condition are included in the new list.

4.3 Practical Example

Imagine that we have a list of IP addresses and want to select only those belonging to a particular network range.

ip_addresses = [
    "192.168.1.10",
    "10.0.0.5",
    "192.168.1.20",
    "172.16.0.8"
]

filtered_ips = [
    ip for ip in ip_addresses
    if ip.startswith("192.168.")
]

print(filtered_ips)

Output:

['192.168.1.10', '192.168.1.20']

This is a simple example of how list filtering can help process network-related information.


5. List Operators and Built-in Functions

Python provides several operators and built-in functions that work with lists.

5.1 The in Operator

The in operator checks whether a particular element exists inside a list.

tools = ["Nmap", "Wireshark", "Burp Suite"]

print("Nmap" in tools)

Output:

True

5.2 The not in Operator

The not in operator checks whether an element does not exist in a list.

tools = ["Nmap", "Wireshark", "Burp Suite"]

print("Metasploit" not in tools)

Output:

True

5.3 The + Operator

The + operator combines two lists into a new list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

combined = list1 + list2

print(combined)

Output:

[1, 2, 3, 4, 5, 6]

5.4 The * Operator

The * operator repeats the elements of a list.

numbers = [1, 2, 3]

print(numbers * 3)

Output:

[1, 2, 3, 1, 2, 3, 1, 2, 3]

5.5 The del Statement

The del statement removes an element from a list using its index.

tools = ["Nmap", "Wireshark", "Burp Suite"]

del tools[1]

print(tools)

Output:

['Nmap', 'Burp Suite']

It can also delete multiple elements using slicing.

numbers = [1, 2, 3, 4, 5]

del numbers[1:3]

print(numbers)

Output:

[1, 4, 5]

5.6 Built-in Functions for Lists

Python includes several built-in functions that work with lists.

FunctionDescription
len(list)Returns the number of elements.
min(list)Returns the smallest element.
max(list)Returns the largest element.
sum(list)Calculates the total of numeric elements.
sorted(list)Returns a new sorted list.

Example:

numbers = [10, 5, 30, 15, 20]

print(len(numbers))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
print(sorted(numbers))

Output:

5
5
30
80
[5, 10, 15, 20, 30]

6. List Methods

Python provides several methods specifically designed to manipulate lists.

6.1 append()

The append() method adds an element to the end of a list.

tools = ["Nmap", "Wireshark"]

tools.append("Burp Suite")

print(tools)

Output:

['Nmap', 'Wireshark', 'Burp Suite']

6.2 index()

The index() method returns the position of the first occurrence of an element.

tools = ["Nmap", "Wireshark", "Burp Suite"]

print(tools.index("Wireshark"))

Output:

1

If the element does not exist, Python raises a ValueError.

6.3 insert()

The insert() method adds an element at a specific position.

tools = ["Nmap", "Burp Suite"]

tools.insert(1, "Wireshark")

print(tools)

Output:

['Nmap', 'Wireshark', 'Burp Suite']

6.4 pop()

The pop() method removes an element and returns its value.

Without an index, it removes the last element.

tools = ["Nmap", "Wireshark", "Burp Suite"]

removed_tool = tools.pop()

print(removed_tool)
print(tools)

Output:

Burp Suite
['Nmap', 'Wireshark']

You can also specify an index:

tools = ["Nmap", "Wireshark", "Burp Suite"]

tools.pop(1)

print(tools)

Output:

['Nmap', 'Burp Suite']

6.5 sort()

The sort() method sorts the elements of a list in place.

numbers = [5, 2, 8, 1, 9]

numbers.sort()

print(numbers)

Output:

[1, 2, 5, 8, 9]

To sort in descending order:

numbers = [5, 2, 8, 1, 9]

numbers.sort(reverse=True)

print(numbers)

Output:

[9, 8, 5, 2, 1]

Important: sort() modifies the original list and returns None. Use sorted() when you want to create a separate sorted list without changing the original.


7. Nested Lists

A nested list is a list that contains one or more lists as its elements.

This allows us to organize related data into multiple levels.

Example:

students = [
    ["Alice", 21],
    ["Bob", 23],
    ["Charlie", 22]
]

print(students)

Output:

[['Alice', 21], ['Bob', 23], ['Charlie', 22]]

7.1 Accessing Nested List Elements

To access an element inside a nested list, we use multiple indexes.

students = [
    ["Alice", 21],
    ["Bob", 23],
    ["Charlie", 22]
]

print(students[0][0])
print(students[0][1])
print(students[1][0])

Output:

Alice
21
Bob

The first index selects the inner list, while the second index selects an element inside that list.

7.2 Modifying Nested Lists

We can also modify individual elements inside nested lists.

students = [
    ["Alice", 21],
    ["Bob", 23],
    ["Charlie", 22]
]

students[1][1] = 24

print(students)

Output:

[['Alice', 21], ['Bob', 24], ['Charlie', 22]]

Nested lists are useful when working with structured information, tables, grids, and datasets.


8. Dictionaries

A dictionary is a collection of key-value pairs.

Each item in a dictionary consists of:

  • A key.

  • A corresponding value.

Dictionaries are written using curly brackets {}.

Example:

student = {
    "Name": "Alice",
    "Age": 21,
    "Major": "IS"
}

print(student)

Output:

{'Name': 'Alice', 'Age': 21, 'Major': 'IS'}

In this example:

KeyValue
NameAlice
Age21
MajorIS

The key "Name" has a value of "Alice", the key "Age" has a value of 21, and the key "Major" has a value of "IS".

Unlike lists, dictionaries are accessed using keys rather than numerical indexes.

8.1 Accessing Dictionary Values

You can retrieve a value by specifying its corresponding key.

student = {
    "Name": "Alice",
    "Age": 21,
    "Major": "IS"
}

print(student["Name"])
print(student["Age"])

Output:

Alice
21

Trying to access a key that does not exist using square brackets raises a KeyError.

8.2 Adding and Modifying Dictionary Items

You can add a new key-value pair by assigning a value to a new key.

student = {
    "Name": "Alice",
    "Age": 21
}

student["Major"] = "IS"

print(student)

Output:

{'Name': 'Alice', 'Age': 21, 'Major': 'IS'}

To modify an existing value, assign a new value to its key.

student["Age"] = 22

print(student)

Output:

{'Name': 'Alice', 'Age': 22, 'Major': 'IS'}

8.3 The get() Method

The get() method retrieves a value using its key.

Unlike square bracket access, get() returns None by default when the key does not exist, instead of raising a KeyError.

student = {
    "Name": "Alice",
    "Age": 21
}

print(student.get("Name"))
print(student.get("Major"))

Output:

Alice
None

You can also specify a default value:

print(student.get("Major", "Not specified"))

Output:

Not specified

8.4 The keys() Method

The keys() method returns all the keys in a dictionary.

student = {
    "Name": "Alice",
    "Age": 21,
    "Major": "IS"
}

print(student.keys())

Output:

dict_keys(['Name', 'Age', 'Major'])

8.5 The values() Method

The values() method returns all the values stored in a dictionary.

print(student.values())

Output:

dict_values(['Alice', 21, 'IS'])

8.6 The items() Method

The items() method returns the dictionary's key-value pairs.

print(student.items())

Output:

dict_items([('Name', 'Alice'), ('Age', 21), ('Major', 'IS')])

This method is particularly useful when looping through dictionaries.

8.7 Looping Through Dictionaries

You can loop through a dictionary to access its keys and values.

student = {
    "Name": "Alice",
    "Age": 21,
    "Major": "IS"
}

for key, value in student.items():
    print(key, ":", value)

Output:

Name : Alice
Age : 21
Major : IS

8.8 Removing Dictionary Items

Python provides different ways to remove dictionary entries.

The pop() method

Removes a specified key and returns its value.

student = {
    "Name": "Alice",
    "Age": 21,
    "Major": "IS"
}

student.pop("Age")

print(student)

Output:

{'Name': 'Alice', 'Major': 'IS'}

The del statement

Deletes a specified key-value pair.

del student["Major"]

print(student)

Output:

{'Name': 'Alice'}

The clear() method

Removes all items from the dictionary.

student.clear()

print(student)

Output:

{}

8.9 Other Dictionary Operations

OperationDescription
len(dictionary)Returns the number of items.
key in dictionaryChecks whether a key exists.
key not in dictionaryChecks whether a key does not exist.
dictionary.update()Adds or updates multiple items.
dictionary.copy()Creates a shallow copy.
dictionary.pop(key)Removes a specified key and returns its value.
dictionary.clear()Removes all dictionary items.
del dictionary[key]Deletes a specific key-value pair.

Example using update():

student = {
    "Name": "Alice",
    "Age": 21
}

student.update({
    "Major": "IS",
    "Country": "UAE"
})

print(student)

Output:

{'Name': 'Alice', 'Age': 21, 'Major': 'IS', 'Country': 'UAE'}

One important detail: dictionary keys must be unique. Assigning a value to an existing key replaces its previous value.


9. Practical Exercises

Now it's time to apply what you've learned.

Try solving these exercises independently before checking your code against the examples in this tutorial.

Exercise 1 – String Methods

Create a string containing " CYBERSECURITY PYTHON ".

Use string methods to:

  1. Remove surrounding whitespace.

  2. Convert the string to lowercase.

  3. Replace "python" with "programming".

  4. Count the number of characters.

Exercise 2 – Function Parameters

Create a function that accepts:

  1. One required positional argument.

  2. Additional positional arguments using *args.

  3. Additional keyword arguments using **kwargs.

Print each group separately.

Exercise 3 – List Indexing

Create a list containing five cybersecurity tools. Display the first, third, and last elements.

Exercise 4 – List Manipulation

Create a list of numbers. Add two elements, insert another element at a specific position, remove one element, and sort the list.

Exercise 5 – List Filtering

Create a list containing numbers from 1 to 20. Use list comprehension to create a new list containing only numbers divisible by three.

Exercise 6 – Nested Lists

Create a nested list containing three students, their ages, and their majors. Access and display the information of the second student.

Exercise 7 – Dictionary Operations

Create a dictionary representing a computer with the following information:

  • Brand

  • Model

  • Price

  • RAM

Add a new key called Storage, update the price, and display all keys and values.

Exercise 8 – Dictionary Filtering

Create a dictionary containing five employees and their salaries. Use a loop to display only employees earning more than 5,000.

Exercise 9 – String and List Combination

Ask a user to enter several cybersecurity tools separated by commas.

Use split() to convert the input into a list, then use a loop to display each tool separately.

Exercise 10 – Mini Project: Network Asset Inventory

Create a simple network asset inventory using a list of dictionaries.

Each dictionary should represent one network device and contain:

  • Device name.

  • IP address.

  • Operating system.

  • Status.

Your program should:

  1. Store at least three network devices.

  2. Display all registered devices.

  3. Allow a user to search for a device by its name.

  4. Display the device's IP address and operating system.

  5. Use a condition to identify whether the device is online or offline.


10. Conclusion

Congratulations! You've completed Level 3 of the Python Fundamentals series.

In this tutorial, we explored several important Python concepts:

  • Common string methods and string manipulation.

  • Positional-or-keyword parameters.

  • Variable-length positional arguments using *args.

  • Variable-length keyword arguments using **kwargs.

  • Creating and accessing lists.

  • List indexing and slicing.

  • Filtering elements using list comprehension.

  • List operators, built-in functions, and methods.

  • Nested lists.

  • Creating and manipulating dictionaries.

  • Dictionary methods and operations.

These concepts are essential when working with structured data and developing more advanced Python applications.

Applying These Concepts to Cybersecurity

Python is particularly useful in cybersecurity because security-related tasks often involve processing large amounts of information.

For example:

  • String methods help process log entries, HTTP headers, and command output.

  • Function arguments allow us to build flexible and reusable security scripts.

  • Lists allow us to manage IP addresses, ports, domains, and discovered assets.

  • Dictionaries allow us to organize network devices, scan results, and structured security information.

  • List comprehension makes it easier to filter and process collected data.

As we continue progressing through Python, we'll apply these concepts to increasingly practical security automation projects.

Keep learning, keep experimenting, and keep building.

Comments

Popular posts from this blog

Information disclosure in version control history

Linux AAA

Hashcat LAB