Module 3: Work with Strings and Lists 

Spread the love

INTRODUCTION – Work with Strings and Lists

In this elaborate module, the learners will delve much deeper into the versatile world of Python programming in terms of enhancing their prowess with strings and lists. It would explore most of the methods designed for these basic data types, with the intention of equipping learners with richer tools for handling data and solving algorithmic problems in the larger scale. Application in practice would compel the learners to bring together what they have learned to produce a small yet effective algorithm.

In fact, this journey continues further with what is known as regular expressions, some helpful insights on this big picture tool used for pattern matching in strings. The course will cover intricate details in regular expressions to familiarise the participants with the way to search and identify specific patterns from textual data. Not only does this module teach participants higher Python programming skills, but it also nurtures an ability to use them in real-life contexts of solving problems.

Learning Outcomes

  • Make use of strings and lists effectively with Python.
  • Create a simple algorithm.
  • Apply regular expressions in extracting information from texts.

TEST YOUR KNOWLEDGE: WORK WITH STRINGS

1. Which of the following statements correctly describes strings? Select all that apply.

  • Strings are immutable. (CORRECT)
  • Strings must be placed in brackets ([ ]).
  • Strings cannot contain numeric characters.
  • Strings must be placed in quotation marks (” “). (CORRECT)

In Python, a string should be enclosed with either single quotes (‘) or double quotes (“). One of the important properties of strings is that they are immutable, which means, once any value is assigned to a string, it cannot be modified. If you attempt to modify a string, you won’t get it modified, rather you will get a new string.

2. What does the following code return?

device_id = "uu0ktt0vwugjyf2"
print(device_id[2:5])
  • “u0kt”
  • “0kt” (CORRECT)
  • “u0k”
  • “0ktt”

The above code outputs “0kt”. It employs bracket notations to fetch out a slice of the value stored inside the variable device_id. Indices start at 0 in python. It takes the characters from character number 2 to character number 4 and excludes the one situated at character number 5. The syntax of slicing is generally device_id[start:end], and where start indicates the starting index and end indicates the ending index.

3. What does the following code display?

device_id = "Tj1C58Dakx"
print(device_id.lower())
  • “tj1C58Dakx”
  • “Tj1C58Dakx”
  • “tj1c58dakx” (CORRECT)
  • “TJ1C58DAKX”

This is what the code prints: “tj1c58dakx”. .lower() is the method that allows to convert Upper cases in a string into Lower cases only.

4. You want to find the index where the substring “192.168.243.140” starts within the string contained in the variable ip_addresses. Complete the Python code to find and display the starting index. (If you want to undo your changes to the code, you can click the Reset button.)

"192.168.243.140" Cybersecurity - Course 7
"192.168.243.140" Cybersecurity - Course 7 - Answer

What index does the substring “192.168.243.140” start at?

  • 31
  • 32 (CORRECT)
  • 34
  • 33

“The sub-string” 192.168.243.140 “starts from index 32 and you can know this with ip_addresses.index(“192.168.243.140″). Note that, Python finds using 0-based index.”

5. What does the code print(“HELLO”[2:4]) output?

  • “LL” (CORRECT)
  • “E”
  • “EL”
  • “LLO”

The print command: print(“HELLO”[2:4]) displays”LL”. In Python slicing, the first index is supposed to be included in the output while the second index is not. This therefore means that it starts form character at index 2 and ends just before index 4, thus including characters at indices 2 and 3.

TEST YOUR KNOWLEDGE: WORK WITH LISTS AND DEVELOP ALGORITHMS

1. Review the following code:

my_list = ["a", "b", "c", "d"]
my_list[2] = 4
print(my_list)

What will it display?

  • [“a”, “b”, “4”, “d”]
  • An error message
  •  [“a”, “b”, 4, “d”] (CORRECT)
  •  [“a”, 4, “c”, “d”]

It will show the array [“a”, “b”, 4, “d”]. This one will reassign element at index 2 in the list my_list. Since index 2 signifies the third element in the list, therefore the string “c” has simply been replaced by integer 4.

2. You are working with the list [“cwvQSQ”,”QvPvX5″,”ISyT3a”,”S7vgN0″]. Its elements represent machine IDs, and the list is stored in a variable named machine_ids. Which line of code will add the ID of “yihhLL” at index 3?

  • machine_ids.insert(“yihhLL”,3)
  • machine_ids.append(“yihhLL”,3)
  • machine_ids.insert(3,”yihhLL”) (CORRECT)
  • machine_ids.append(“yihhLL”)

The command machine_ids.insert(3, “yihhLL”) adds machine ID “yihhLL” into the current machine_ids list at index 3. Using the .insert() method, one can insert an element at a certain position within a list. The .insert() method has two parameters: the first parameter gives the index to insert the element into, and the second gives the element to add.

3. Which line of code will remove the username “tshah” from the following list?

access_list = [“elarson”, “bmoreno”, “tshah”, “sgilmore”]

  • access_list.remove(3)
  • access_list.remove(“tshah”) (CORRECT)
  • access_list.remove(2)
  • access_list[“tshah”].remove()

Code access_list.remove(“tshah”) will remove the username “tshah” from the list: The .remove() method removes the first occurrence of that element in the list. It needs an argument of the element you want to remove, as access_list.remove( “tshah”) does, and therefore it removes the first occurrence of the string username “tshah”. If that element is not found, it raises a ValueError.

4. As a security analyst, you are responsible for developing an algorithm that automates removing usernames that match specific criteria from an access list. What Python components would help you implement this? Select three answers.

  • A for loop that iterates through the usernames in the access list (CORRECT)
  • The .append() method
  • The .remove() method (CORRECT)
  • An if statement that compares a username to the criteria for removal (CORRECT)

The routine should iterate through the usernames in the access list. For each iteration, it will check whether the username meets the specified requirement. Then it will remove the username if it is found. The conditional statement checks if the current username is to be accepted according to the specified condition.

5. In the list [“elarson”, “bmoreno”, “tshah”, “eraab”], which element has an index of 3?

  • “bmoreno”
  • “tshah”
  • “eraab” (CORRECT)
  • “elarson”

You are fine! List indices in Python start from 0. Thus, the index of element “eraab” in the list [“elarson”, “bmoreno”, “tshah”, “eraab”] is 3, which implies its position is the fourth in this list.

TEST YOUR KNOWLEDGE: REGULAR EXPRESSIONS

1. Which regular expression symbol represents one or more occurrences of a specific character?

  • (CORRECT)
  • *
  • \d
  • \w

The + sign in regex is a quantifier used for at least one instance of the prior character or group.

2. As a security analyst, you are responsible for finding employee IDs that end with the character and number sequence “a6v”. Given that employee IDs consist of both numbers and alphabetic characters and are at least four characters long, which regular expression pattern would you use?

  • “\w+a6v” (CORRECT)
  • “\wa6v”
  • “\w*a6v”
  • “a6v”

It is indicated that there is at least an alphanumeric character before “a6v” in such a way that it must have one or several alphanumeric characters at the end of “a6v”. Thus, the string includes at least an alphanumeric character before ending with “a6v”. Here is an added rephrased version of the preceding explanation:

3. You have imported the re module into Python with the code import re. You want to use the findall() function to search through a string. Which function call enables you to search through the string contained in the variable text in order to return all matches to a regular expression stored in the variable pattern?

  • re.findall(text, pattern)
  • findall(text, pattern)
  • findall(pattern, text)
  • re.findall(pattern, text) (CORRECT)

The function re.findall(pattern, text) helps in finding all the matches of a regular expression in a string. However, it can be accessed only if you import the re module. The argument pattern is the regular expression in search of. The other argument, text, is the string value where one has to search for this pattern. The returned result will be all matches found.

4. Which of the following strings would Python return as matches to the regular expression pattern “\w+”? Select all that apply.

  • “FirstName” (CORRECT)
  • “”
  • “3” (CORRECT)
  • “#name”

The regular expression pattern \w+ is matched by the strings “3” and “FirstName”. The \w symbol matches any alphanumeric character (letter and digit) and in conjunction with the + suffix indicates there will be one or more such occurrences. Since “FirstName” consists of more than one alphanumeric character, it will fit the pattern. Meanwhile, “3” consists of just one alphanumeric character. Hence both these strings are matched by this regular expression.

5. Which string matches with the regular expression “b\wa+b”?

  • “bkaaab” (CORRECT)
  • “yaaab”
  • “cba”
  • “baaa”

The string “bkaab” is matching against the regular expression “b\wa+b”. The first letter must be b. Following that, the “\w” symbol matches any alphanumeric character, such as “k”. The plus symbol indicates that the character it follows, in this case “a”, must appear at least one or more times. Finally, the string must terminate with “b”.

MODULE 3 CHALLENGE

1. What is the output of the following code?

print(len("125"))
  • 5
  • (CORRECT)
  • 10
  • 8

2. Which line of code returns a copy of the string “bmoreno” as “BMORENO”?

  • print(upper.”bmoreno”())
  • print(“bmoreno”.upper()) (CORRECT)
  • print(“bmoreno”(upper))
  • print(upper(“bmoreno”))

3. In the string “network”, which character has an index of 1?

  • “e” (CORRECT)
  • “n”
  • “k”
  • “t”

4. You need to take a slice from a network ID. Specifically, you must extract the characters with indices of 6 through 10. Complete the Python code to take this slice and display it. (If you want to undo your changes to the code, you can click the Reset button.)

network ID - course 7 - work with string and list
network ID - course 7 - work with string and list - answer

What string does the code output?

  • “85n52” (CORRECT)
  • “5n528”
  • “585n5”
  • “m585n”

5. What is the output of the following code?

username_list  = ["elarson", "bmoreno", "tshah"] 
device_id_list = ["us2c0R5", "2R78TBR", "bt3MIEz"]
print(username_list + device_id_list)
  •  [“elarson”, “us2c0R5”, “bmoreno”, “2R78TBR”, “tshah”, “bt3MIEz”]
  •  [“us2c0R5”, “2R78TBR”, “bt3MIEz”, “elarson”, “bmoreno”, “tshah”]
  • An error message
  •  [“elarson”, “bmoreno”, “tshah”, “us2c0R5”, “2R78TBR”, “bt3MIEz”] (CORRECT)

6. A variable named my_list contains the list [1,2,3,4]. Which line of code adds the element 5 to the end of the list?

  • my_list.insert(4,5) (CORRECT)
  • my_list.insert(5,5)
  • my_list.insert(5,4)
  • my_list.insert(5)

Strings must be added into the quote mark. They are unchangeable, meaning that after they are created and assigned a value, they cannot be changed.

7. Fill in the blank: Determining that you need to use string slicing and a for loop to extract information from items in a list is part of creating a(n) _____.

  • regular expression
  • append
  • index
  • algorithm (CORRECT)

8. Which of the following strings would Python return as matches to the regular expression of “\w+”? Select all that apply.

  • “email@email.com”
  • “network” (CORRECT)
  • “9210” (CORRECT)
  • “email123” (CORRECT)

9. What module do you need to import to use regular expressions in Python?

  • re (CORRECT)
  • time
  • os
  • csv

10. What does the code username_list.append(“bmoreno”) method do?

  • Updates all instances of “bmoreno” in the username_list list to uppercase letters
  • Returns all matches to the pattern “bmoreno” in the username_list list
  • Adds “bmoreno” to the end of the username_list list (CORRECT)
  • Inserts “bmoreno” at the beginning of the username_list list

11. Which line of code converts the integer 7 to a string?

  • str(7) (CORRECT)
  • string(“7”)
  • string(7)
  • str(“7”)

12. Which line of code returns a copy of the string “HG91AB2” as “hg91ab2”?

  • print(“HG91AB2″(lower))
  • print(“HG91AB2”.lower()) (CORRECT)
  • print(lower.”HG91AB2″())
  • print(lower(“HG91AB2”))

13. What is the index of the character “4” in the string “h204D3921”?

  • (CORRECT)
  • 2
  • 5
  • 4

14. You need to take a slice from an employee ID. Specifically, you must extract the characters with indices of 3, 4, 5, and 6. Complete the Python code to take this slice and display it. (If you want to undo your changes to the code, you can click the Reset button.)

Complete the Python code - Question

What string does the code output?

Complete the Python code - Answer
  • “237x”
  • “x430”
  • “7×43” (CORRECT)
  • “37×4”

15. What is the output of the following code?

list1 = [1, 2, 3] 
list2 = ["a", "b", "c"]
print(list1 + list2)
  •  [6, “abc”]
  • An error message
  •  [1, 2, 3, “a”, “b”, “c”] (CORRECT)
  •  [1, “a”, 2, “b”, 3, “c”]

16. What is an algorithm?

  • A function that finds matches to a pattern
  • A set of guidelines to keep code consistent
  • A set of rules to solve a problem (CORRECT)
  • A function that returns information

Quotation marks enclose strings. Once created and assigned a value, they become immutable, implying that strings cannot be modified.

17. What does the \w symbol match to in a regular expression?

  • Any character and symbol
  • Any alphanumeric character (CORRECT)
  • Any number
  • Any letter

18. What does the re.findall() function return?

  • All possible regular expressions that match to a given string
  • A list of all matches to a regular expression in a given string (CORRECT)
  • The first match to a regular expression in a given string
  • All occurrences of the pattern “re” in a given string

19. Which code joins a list of new_users to a list of approved_users and assigns the value to a third variable named users?

  • users(new_users, approved_users)
  • users = new_users + approved_users (CORRECT)
  • users = insert(new_users, approved_users)
  • users(new_users[1], approved_users[2])

20. Which of the following strings would Python return as matches to the regular expression pattern of  “\w”? Select all that apply.

  • “1B”
  • “security”
  • “W” (CORRECT)
  • “2” (CORRECT)

21. You have imported the re module into Python with the code import re. Which code searches the device_ids string variable for a pattern of “r15\w+”?

  • findall(“r15\w+”, device_ids)
  • re.findall(device_ids, “r15\w+”)
  • findall(device_ids, “r15\w+”)
  • re.findall(“r15\w+”, device_ids) (CORRECT)

22. Which method adds input to the end of a list?

  • .lower()
  • .insert()
  • .append() (CORRECT)
  • .index()

23. Which line of code returns the number of characters in the string assigned to the username variable?

  • print(len(username)) (CORRECT)
  • print(username.len())
  • print(str(username))
  • print(username.str())

24. What is the result when .upper() is applied to a string?

  • A copy of the string is returned with all uppercase letters. (CORRECT)
  • The character that appears most frequently in the string is extracted from it and returned.
  • The value of the string is reassigned to the value of the string in the line preceding it.
  • The value of the string is reassigned to contain all uppercase letters.

25. What is the output of the following code?

approved_users = ["bmoreno", "elarson", "tshah", "eraab"]
print(approved_users[1])
  • [“bmoreno”, “elarson”, “tshah”, “eraab”, 1]
  •  [1, “bmoreno”, “elarson”, “tshah”, “eraab”]
  • “bmoreno”
  • “elarson” (CORRECT)

26. What does the code device_ids.append(“h32rb17”) do?

  • Inserts “h32rb17” at the beginning of the device_ids list
  • Updates all instances of “h32rb17” in the device_ids list to uppercase letters
  • Returns all matches to the pattern “h32rb17” in the device_ids list
  • Adds “h32rb17” to the end of the device_ids list (CORRECT)

27. What is the index of the character “c” in the string “encryption”?

  • 4
  • 3
  • 1
  • (CORRECT)

28. You need to take a slice from a device ID. Specifically, you must extract the characters with indices of 8, 9, and 10. Complete the Python code to take this slice and display it. (If you want to undo your changes to the code, you can click the Reset button.)

extract the characters with indices of 8, 9, and 10 - Question

What string does the code output?

extract the characters with indices of 8, 9, and 10 - Answer
  • “1w3”
  • “81w”
  • “w36” (CORRECT)
  • “363”

CONCLUSION – Work with Strings and Lists

Overall, this module is a bridge between the previous initiation sessions and the future modules of the Python programming journey with respect to the string and list manipulations. The participants improve their skills in the use of advanced techniques available for these data types and apply concepts from algorithm studies into their general repertoire.

The use of the regular expression reinforces the participants’ ability to recognize patterns in strings, thus deepening their knowledge of data analysis and manipulation. As participants undergo this extensive learning risk, they sharpen their skills in Python and develop a problem-solving mentality required in the real world.

Leave a Comment