Docsity

Python String and List Manipulation: A Comprehensive Guide with Exercises and Solutions, Exams of Computer Science

Toggle sidebar
bg1
Python C859 Questions and Complete
Solutions Graded A+
Minimum field width with strings - Answer: print('Student name (%5s)' % 'Bob'
the 5 specifies that there are a minimum of 5 characters and thus the print out would be ( Bob)
Conversion flags - Answer: alter the output of conversion specifiers
%08d adds leading zeros to the minimum width of 8 characters
precision components(Rounding) - Answer: Indicates how many digits to the right of the decimal should
be included
'%.1f' % 1.725 indicates a precision of 1 resulting in 1.7
.replace() - Answer: replace(old,new,count)
count replaces only the first occurrence
count can be left out
translation = translation.replace('one', 'uno')
.find(x) - Answer: Returns the position of the first occurrence of item x in the string
if my_str is 'Boo Hoo!'
my_str.find('!') Returns 7
my-str.find('Boo') Returns 0
my_str.find('oo') returns 1
find(x, start) - Answer: Same as find(x) but begins the search at position start
find(x, start, end) - Answer: Same as find(x,start) but stops the search at position end
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Python String and List Manipulation: A Comprehensive Guide with Exercises and Solutions and more Exams Computer Science in PDF only on Docsity!

Python C859 Questions and Complete

Solutions Graded A+

Minimum field width with strings - Answer: print('Student name (%5s)' % 'Bob' the 5 specifies that there are a minimum of 5 characters and thus the print out would be ( Bob) Conversion flags - Answer: alter the output of conversion specifiers %08d adds leading zeros to the minimum width of 8 characters precision components(Rounding) - Answer: Indicates how many digits to the right of the decimal should be included '%.1f' % 1.725 indicates a precision of 1 resulting in 1. .replace() - Answer: replace(old,new,count) count replaces only the first occurrence count can be left out translation = translation.replace('one', 'uno') .find(x) - Answer: Returns the position of the first occurrence of item x in the string if my_str is 'Boo Hoo!' my_str.find('!') Returns 7 my-str.find('Boo') Returns 0 my_str.find('oo') returns 1 find(x, start) - Answer: Same as find(x) but begins the search at position start find(x, start, end) - Answer: Same as find(x,start) but stops the search at position end

rfind(x) - Answer: Same as find but searches the string in reverse, returning the last occurrence in the string count(x) - Answer: Returns the number of times x occurs in the string using in operator to check if a character or substring is contained in the string - Answer: if 'b' in my_string Comparing Strings - Answer: may be compared using relational operators (<> <= etc..) equality operators (==,!=) membership operators (in,not in) identity operators (is, is not) my_str = 'Hello' my_str == 'Hello" evaluates to True relational comparison will compare the ASCII unicode values. if a string is shorter with all the same characters then the shorter is considered less than Do not use identity operators where you should be using an equality operator comparisons are case sensitive isalnum() - Answer: Returns True if all characters int he string are lowercase or uppercase letters, or the numbers 0- isdigit() - Answer: Returns True if all characters are the numbers 0- islower() - Answer: Returns True if all characters are lowercase letters isupper() - Answer: Returns True if all characters are uppercase letters

my_str = '@'.join(['billgates', 'microsoft']) binds the name my_str to a new string object with the value 'billgates@microsoft' each element from left to right is concatenated together. The separator can be any string including multiple characters or an empty string charater. ''.join will return the list as a string w/out separators. string format method - Answer: positional= 'The {1} in the {0}'.format('hat','cat') The cat in the hat Inferred positional 'The {} in the {}'.format("cat",'hat') The cat in the hat Named 'The {animal} in the {headwear}.format(animal = 'cat', headwear='hat') The cat in the hat lists - Answer: Container object that groups related objects together. Has a sequence that is maintained left to right Elements of the list can be accessed through indexing Each element can be a different data type inclusive of nested lists within the list. Lists are mutable (In place modification) Creating a list - Answer: my_list = [1,2,3] list(iterable)

Retrieving an element from a list - Answer: my_list[list element index] Get a new list containing some of another list's elements - Answer: my_list[start:end] retrieves the indexed values of my_list Add a list to the end of another list - Answer: my_list1 + my_list Change the value of an element within a list - Answer: my_list[index number] = x Delete an element from a list - Answer: del my_list[index number] create a copy of a list - Answer: your_list = my_list[:] my_list is the original list Add an item to the end of a list - Answer: list.append(x) add all items in [x] to a list - Answer: list.extend([x]) insert x into list before position i - Answer: list.insert(i,x) Remove the first item from list with value x - Answer: list.remove(x) Remove and return last item in list - Answer: list.pop() Remove and return item at position i in list - Answer: list.pop(i) Sort the items of list in place - Answer: list.sort()

print(max([-3, 5, 25])) 25 min(list) - Answer: Get the minimum element in the list print(min([-3, 5, 25]))- 3 sum(list) - Answer: Get the sum of all elements in the list print(sum([-3, 5, 25])) 27 Accessing a nested list - Answer: my_list = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] my_list[0] = 'a' 'b' mylist[0][1] = 'b' Iterating a nested loop with multiple rows - Answer: Iterating through multidimensional lists using enumerate() - Answer: slicing - Answer: [1:5} Beginning at index 1 and continuing up to but not including index 5 negative slicing - Answer: [3:-1} start one index position from end of the list and include the three elements prior to it. stride of slice - Answer: [0:5:2] The 2 indicates it has a stride of two which would skip every other element Get a list from starting point to end of list - Answer: my_list[start:end]

Get a list from start to end of the list - Answer: my_list[start:] Get a list from the beginning of list to end (minus 1) - Answer: my_list[:end] Get a copy of list - Answer: my_list[:] Modifying a list with loop iteration - Answer: # Change negative values to 0 for pos in range(len(nums)): if nums[pos] < 0: nums[pos] = 0 The square brackets must be included in the latter half of the loop. it is best to make a copy of a list if you are deleting items from it with the iteration. This is because as an item is deleted, the remaining elements are indexed to the left which would skip over the next element Copying a list within a for loop - Answer: for item in my_list[:] List comprehensions - Answer: new_list = [expression for name in iterable] expression evaluates each item of the list name provides the variable component to bind iterable is a list or something else to iterate over Always surrounded by brackets Builds and returns a new list object rather than the modification that is available with a for loop list comprehension for converting every element to a string within a list - Answer: my_list = [str(i) for i in my_list]

Reverse sorting a list - Answer: sorted_list = sorted(my_list, reverse=True) Dictionaries - Answer: {'key': 'Value', 'key': 'Value} dict(Bobby='805-555-2232', Johnny='951-555-0055') Container object key-value pairs each key is associated with a value mutable retrieve the value associated with a dictionary key - Answer: my_dict[key] Add an entry into a dictionary or modify the existing entry - Answer: my_dict[key] = value Delete the key entry from a dictionary - Answer: del my_dict[key] Test for existence of key in my_dict - Answer: key in my_dict Remove all items from a dictionary - Answer: my_dict.clear() Read the value of the key entry from a dictionary and return default if no value exists - Answer: my_dict.get(key,default) Merge a dictionary with another dictionary. Dictionary one will have existing entries overwritten if the same keys exist in dictionary two - Answer: my_dict1.update(my_dict2) Remove and return the key value from the dictionary. If key deos not exist, then default is returned - Answer: my_dict.pop(key,default)

Iterating over the key and values of a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda, calories in num_calories.items(): .items() is the keyword that allows for both items to be iterated over iterating over the keys in a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda in num_calories.keys(): .keys() is the keyword that allows for both items to be iterated over iterating over the values in a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda in num_calories.values(): .values() is the keyword that allows for both items to be iterated over nested dictionary - Answer: {'D1': {'D2': 'x'}} music = { 'Pink Floyd': { 'The Dark Side of the Moon': { 'songs': [ 'Speak to Me', 'Breathe', 'On the Run'], 'year': 1973, 'platinum': True }, etc.. } Code that potentially may produce an exception should be placed in a - Answer: Try Block except block - Answer: A block of code that is executed if the prior try block causes an exception

except ValueError as excpt - Answer: creates a new variable except that the exception handling code might inspect for details about the exception instance. Printing the exception prints the string argument passed to the exception when raised. exceptions within functions - Answer: raise Valuerror() can be placed within a function as long as the executed code below the function is placed within a try block execution of the raise statement within the function causes automatic exiting of the function finally - Answer: a clause of a try statement that allows a programmer to specify clean-up actions that are always executed this is always the last code executed before the try block finishes if no exception occurs, then execution continues in the finally clause and then proceeds to the rest of the program Custom exception type - Answer: an exception type that is defined by the programmer outside of the built in exceptions good practice is to include error at the end of the custom name a new class must be defined class LessThanZeroError(Exception): def ____init____(self,value): self.value = value module - Answer: a file containing Python code that can be imported and used by scripts, other modules, or the interactive interpreter

filename should end with .py Importing a module - Answer: executing the code contained by the module and making the definitions within the module available for use by the importing program good practice is to place import statements at the top of a file import "filename" without the .py extension The filename is case sensitve overriding the definitions of an imported function - Answer: module_name.value/variable changed = changed value this is only temporary in your existing script and will not change the imported file permanently built in module - Answer: one that comes pre-installed with python environmental variable - Answer: stored in the computers operating system and can be accessed by every program running on the computer changing PYTHONPATH - Answer: set PYTHONPATH="c:\dir1;c:\other\directory". importing specific names from a module - Answer: from module_name import name1, name2, ... adds only the specified names to the global namespace and not the whole modue name - Answer: is a global string variable automatically added to every module that contains the name of the module checking if a file is the executing script or an imported module - Answer: if name == "main"

file.close() - Answer: closes a file to where no more reads or writes to the file are allowed file.read() - Answer: returns the file contents as a string my_file.read(500) this would read the first 500 bytes of text file.readlines() - Answer: returns a list of strings where the first element is the contents of the first line, second element is the contents of the second line and so on my_file = open('readme.txt') lines = my_file.readlines() print (lines[1]) This would print the 2nd line of text file.readline() - Answer: returns a single line at a time useful with large files where contents may not fit into the available system memory iterating over a file - Answer: f = open('myfile.txt') for line in f: print(line) f.close() file.write() - Answer: used to store data permanently Only accepts a string argument other data types must be first converted into string

f = open('myfile.txt', 'w') # Open file f.write('Example string:\n test...') # Write string f.close() # Close the file num1 = 5 num2 = 7. num3 = num1 + num f = open('myfile.txt', 'w') f.write(str(num1)) f.write(' + ') f.write(str(num2)) f.write(' = ') f.write(str(num3)) f.close() 'r' - Answer: open the file for reading if file is missing then error will occur 'w' - Answer: open the file for writing if file does not exist then the file is created contents of an existing file are overwritted 'a' - Answer: open the file for appending if file does not exist then the file is created writes are added to the end of existing file contents 'r+' - Answer: specifies to handle the file in update mode

import os p = os.path.join('C:\', 'Users', 'BWayne', 'bat_chopper') if os.path.isfile(p): print('Found a file...') else: print('Not a file...') os.path.getsize(path) - Answer: Returns the size in bytes of the path (The file size) os.walk() - Answer: walks a directory tree, visiting each subdirectory in the specified path used to search for specific files within a directory tree where the exact path is unknown \ and / - Answer: file separators windows will accept either of these bytes() - Answer: used to represent a sequence of single byte values such as binary data These are immutable with statement - Answer: this is considered good practice for opening files to ensure that it is closed when complete can be used to open a file, execute a block of statements, and automatically close the file when complete with open('myfile.txt', 'r') as myfile:

csv.reader - Answer: used to read an imported csv file can also be used to write if the 'r' is changed to 'w' import csv with open('grades.csv', 'r') as csvfile: grades_reader = csv.reader(csvfile, delimiter=',') row_num = 1 for row in grades_reader: print('Row #%d:' % row_num, row) row_num += 1