Changes

Jump to: navigation, search

OPS435 Python Lab 4

23,955 bytes added, 09:26, 21 January 2020
no edit summary
<font color='red'>
'''** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **'''
</font>
= OBJECTIVES =
:The '''first investigation''' in this lab will focus on '''Data Structures'''. Each data structure has its own advantages and limitations. This lab will emphasize the most important differences between them.
= Lab Preparation === Objectives ==The first investigation of this lab we will be working with different data structures. These are stored in a similar way to variables and lists, however they can contain a lot more information and are designed for specific purposes. Each structure has its own advantages and disadvantages, this lab will emphasize where those important differences lay. :The '''second investigation ''' will focus closely on strings. We You have been using and storing strings since our first class, however in this lab we will dive into the more complex nature of string manipulation. Finally, this lab will cover how to use a variety of different regular expression functions, for searching and input validation.== Python Reference ==
= Investigation 1 - Data Structures ==PYTHON REFERENCE = Investigation 1 - Part 1 - Tuple ==A :As you develop your Python Tuple is a number scripting skills, you may start to be "overwhelmed" with the volume of immutable Python valuesinformation that you have absorbed over these labs. This One way to help is similar to a list learn to use online references effectively in order to obtain information regarding Python scripting techniques and tools. :Below is a lot of waystable with links to useful online Python reference sites (by category). You may find these references useful when performing assignments, except that, you cannot change the values insideetc. {| class="wikitable" | style="margin-left:20px; border: 2px solid black;"|- style="border: 2px solid black;font-weight:bold;text-align:center;"| style="border: 2px solid black;" | Data Structures | style="border: 2px solid black;" | Lists &amp; List Comprehension| style="border: 2px solid black;" | Strings| style="border: 2px solid black;" | Regular Expressions| style="border: 2px solid black;" | Miscellaneous |- style="background-color:white;border:none;"| style="border: 2px solid black;" valign="top"| :*[https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences Tuples]:*[https://docs.python.org/3/tutorial/datastructures.html#sets Sets]| style="border: 2px solid black;" | :*[https://docs.python.org/3/tutorial/introduction.html#lists Lists]:*[https://docs.python.org/3/tutorial/datastructures.html#more-on-lists More on Lists]:*[https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions List Comprehensions]<pre>| style="border: 2px solid black;" valign="top"| ipython:*[https://docs.python.org/3/tutorial/introduction.html#strings Strings]:*[https://docs.python.org/3/library/string.html String Comparisons]t1 | style= "border: 2px solid black;" valign="top"| :*[https://docs.python.org/3/library/re.html Regular Expression Operations]:*[https://docs.python.org/3/howto/regex.html Regular Expressions ('Prime', 'Ix', 'Secundus', 'Caladan'HOWTO)]t2 | style= (1, 2, "border: 2px solid black;" valign="top"| :*[https://docs.python.org/3, 4, 5, 6)/tutorial/datastructures.html#dictionaries Dictionaries] |} </pre>= INVESTIGATION 1: DATA STRUCTURES =
Values from a tuple can be retreived :In this investigation, you will learn several data structures commonly used in the same way as a listPython scripting. These tools include '''lists''', '''tuples''', '''sets''', and '''dictionaries'''.<pre>t1[0]t2[2:4] </pre>== PART 1 - Tuples ==
Or check if :Many often confuse a value exists inside '''tuple''' with a '''list''' (which you learned about in a tupleprevious lab).<pre>A 'Ix' in t1'Geidituple''' is a type of list whose values cannot be changed. In fact, nothing in t1</pre> a tuple can be changed after it's created (like adding, removing list elements).
Try changing a tuple value.<pre>t2[1] = 10</pre>:There are many advantages to using tuples when creating Python scripts:
Did it work? Once created the tuple ::*'''Data protection''' (eg. values will not be able are are NOT allowed to change. If you would like a tuple with different values than the tuple you currently have, so you must create a new one.won't modify them accidentally)<pre>::*Tuples can be used as '''keys in data dictionaries''' (which are NOT allowed to change)t3 = t2[2:3]</pre>:*Tuples allow for '''faster access''' than lists
You however :The term to indicate that a data structure cannot be changed is called '''immutable''' (as opposed to ''"mutable"'' which means the data structure can still use most of the basic operations you might expect from tuplesbe changed).<pre>len(t1) # list the length of the tuplet1 * 3 # repititiont1 + t2 # concatenation, remember this is creating a new tuple, not modifying</pre>
Like :'''Perform the Following Steps:''':#Let's create two tuples in a temporary Python file, so we can learn how to use them and learn how they differ from lists.<br><br>Note: '''tuples are defined by using parenthesis ( )''' as opposed to '''listswhich are defined by using square brackets [ ]'''<source lang="python">t1 = ('Prime', 'Ix', 'Secundus', 'Caladan')t2 = (1, 2, 3, 4, 5, 6)</source>:#Values from a tuple can be retrieved in the same way as a list. For example:<source lang="python">print(t1[0])print(t2[2:4])</source>:#You can also check to see whether a value exists inside a tuple or not. To demonstrate try:<source lang="python">print('Ix' in t1)print('Geidi' in t1)</source>Let's now see how a tuple differs from a list. We will now create a list and note the difference between them:<source lang="python">list2 = [ 'uli101', 'ops235', 'ops335', 'ops435', 'ops535', 'ops635' ]</source>:#See if you can also loop through change the value of your list:<source lang="python">list2[0]= 'ica100'print(list2[0])print(list2)</source>You should have been successful in changing the value of your list.<br><br>:#Now, try changing the value of your previously-created tuple:<source lang="python">t2[1] = 10</source>Did it work? Once created the tuple values will not be able to change.<br><br>If you would like a tuple with different values than the tuple you currently have, then you must create a new one.<br><br>:#The following creates a new tuple (t3) with a contents from a slice of the t2 tuple. Slicing works the same way for tuples.as for lists:<source lang="python">t3 = t2[2:3]</source>:#Also, as with lists, you can use for loops to iterate the values of tuples:<presource lang="python">
for item in t1:
print('item: ' + item)
</presource>
== PART 2 - Sets ==
== Investigation 1 - Part 2 - Set ==Sets are another very similar structure to lists:So far, they can also be modified and changed, unlike the tuple. But sets you have been exposed to two unique characteristics, they structures that are unordered, used to contain data: ''lists'' and they cannot have duplicate values''tuples''. The unordered part provides a added performance from hashing You can modify the values, but also means we cannot pull out within a specific value at list as well as modify the structure of a spefici positionlist (i. Any duplicate entries will immediately be deletede. Sets however are great tools for doing comparisonsadd and remove elements), finding differences in multiple sets, or finding similaritieswhereby you cannot with a tuple. The best part about sets are, they are fast!
Lets create :In this section, you will learn about '''sets'''. A set has similar characteristics as a couple list, but there are two major differing characteristics: ::*Sets are '''un-ordered'''::*Sets '''cannot contain duplicate values''' :Since new duplicate entries will be automatically removed when using sets, they are very useful for performing tasks such as '''comparisons''': '''finding similarities or differences in multiple sets'''. :#Create some sets to work with.in a temporary Python file:<presource lang="python">
s1 = {'Prime', 'Ix', 'Secundus', 'Caladan'}
s2 = {1, 2, 3, 4, 5}
s3 = {4, 5, 6, 7, 8}
</presource>Note: '''Sets are defined by using braces { }''' as opposed to tuples which use parenthesis ( ), or lists which use square brackets [ ]'''<br /><br />:#Try to access a set through the index:<source lang="python">print(s1[0])</source>This should have caused an '''error'''. You cannot access data inside a set this way because the elements inside are '''unordered'''. Instead, you should use the '''in''' method to check to see whether a value is contained in the set:<source lang="python">print('Ix' in s1)print('Geidi' in s1)</source><br>'''Sets can be combined''', but it is important to note that any '''duplicate values (shared among sets) will be deleted'''.<br><br>:#Print the contents of the sets and note the values that are common:<source lang="python">print(s2)print(s3)</source>:#This is how you get a set containing only UNIQUE values (no duplicates) from both sets:<source>print(s2 | s3) # returns a set containing all values from both setsprint(s2.union(s3)) # same as s2 | s3</source>Notice that both methods above have the same result, which one you choose depends purely on your style.<br><br>Instead of combining sets, we can display '''values that are common to both sets'''. This is known in mathematical terms as an '''intersection''' between the lists:<source lang="python">print(s2 & s3) # returns a set containing all values that s2 and s3 shareprint(s2.intersection(s3)) # same as s2 & s3</source>:#Sets can also have their values compared against other sets. First find out what items are in '''s2''' but not in '''s3'''. This is also called a '''difference''':<source lang="python">print(s2)print(s3)print(s2 - s3) # returns a set containing all values in s2 that are not found in s3print(s2.difference(s3)) # same as s2 - s3</source>:#In order to see <u>every</u> difference between both sets, you need to find the '''symmetric difference'''. This will return a set that shows all numbers that both sets do not share together:<source lang="python">print(s2 ^ s3) # returns a set containing all values that both sets DO NOT shareprint(s2.symmetric_difference(s3)) # same as s2 ^ s3</source>Note: the '''set()''' function can convert lists into sets, and the '''list()''' function can convert sets into lists. The operations in this section can only be applied to sets, so if you need to perform a union, intersection, or difference between lists, you need to convert them to sets first. For example:<source lang="python">l2 = [1, 2, 3, 4, 5]l3 = [4, 5, 6, 7, 8]temporary_set = set(l2).intersection(set(l3))new_list = list(temporary_set) # '''set()''' can make lists into sets. '''list()''' can make sets into lists.print(new_list)</source> === Create a Python Script Demonstrating Comparing Sets ===:'''Perform the Following Instructions''':#Create the '''~/ops435/lab4/lab4a.py''' script. The purpose of this script will be to demonstrate the different way of comparing sets. There will be three functions, each returning a different set comparison. :#Use the following template to get started:<source lang="python">#!/usr/bin/env python3 def join_sets(s1, s2): # join_sets will return a set that contains every value from both s1 and s2 def match_sets(s1, s2): # match_sets will return a set that contains all values found in both s1 and s2 def diff_sets(s1, s2): # diff_sets will return a set that contains all different values which are not shared between the sets if __name__ == '__main__': set1 = set(range(1,10)) set2 = set(range(5,15)) print('set1: ', set1) print('set2: ', set2) print('join: ', join_sets(set1, set2)) print('match: ', match_sets(set1, set2)) print('diff: ', diff_sets(set1, set2)) </source>
First, try accessing ::*The join_sets() function should return a set through the index.that contains all values from both sets::*The match_sets() function should return a set that contains all values found in both sets::*The diff_sets() function should return a set that contains all values which are not shared between both sets<pre>::*All three functions should accept '''two arguments''' both are setss1[0]::*The script should show the exact output as the samples</pre>::*The script should contain no errors
You should have received a error, this is not how you access data inside a set because they are unordered:::'''Sample Run 1:'''<source>. Instead you can check to see if a value is inside/lab4a.pyset1: {1, 2, 3, 4, 5, 6, 7, 8, 9}set2: {5, 6, 7, 8, 9, 10, 11, 12, 13, 14}join: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}match: {8, 9, 5, 6, 7}diff: {1, 2, 3, 4, 10, 11, 12, 13, 14}<pre/source>:::'Ix' in s1'Sample Run 2 (with import):'''<source>import lab4aset1 = {1,2,3,4,5}set2 = {2,1,0,-1,-2}print(lab4a.join_sets(set1,set2))# Will output {-2, -1, 0, 1, 2, 3, 4, 5}print(lab4a.match_sets(set1,set2))# Will output {1, 2}print(lab4a.diff_sets(set1,set2))# Will output {-2, -1, 0, 3, 4, 5}</source><ol><li value='Geidi3' style="margin-left:25px;">Download the checking script and check your work. Enter the following commands from the bash shell:<source lang="bash">cd ~/ops435/lab4/pwd #confirm that you are in s1the right directoryls CheckLab4.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab4.pypython3 ./CheckLab4.py -f -v lab4a</source></li><li style="margin-left:25px;">Before proceeding, make certain that you identify all errors in lab4a.py. When the checking script tells you everything is OK - proceed to the next step.</li></preol>
If you would like to combine sets together you can=== Create a Python Script Demonstrating Comparing Lists ===:'''Perform the Following Instructions''':#Create the '''~/ops435/lab4/lab4b.py''' script. Any duplicates that the 2 sets share, The purpose of this script will be deleted. Take a close look at which items are shared between to improve the previous script to perform the setssame joins, matches, and diffs, but this time on lists.:#Use the following as a template:<presource lang="python">s2s3s2 | s3 # returns a set containing all values from both setss2.union(s3) # same as s2 | s3<!/usr/bin/pre>env python3
Instead of combining setsdef join_lists(l1, we can find out what values are in both sets. This is a intersection between the lists.l2):<pre>s2s3s2 & s3 # returns join_lists will return a set containing all values list that s2 contains every value from both l1 and s3 shares2.intersection(s3) # same as s2 & s3</pre>l2
def match_lists(l1, l2):
# match_lists will return a list that contains all values found in both l1 and l2
Lets look at how we can compare the values inside sets. First lets find out what items are in '''s2''' but not in '''s3'''. This is also called a difference. But notice that it only shows values that '''s2''' containsdef diff_lists(l1, specifically values that '''s3''' doesn't have. So this isn't really the true difference between the sets.<pre>s2s3l2):s2 - s3 # returns diff_lists will return a set containing list that contains all different values in s2 that , which are not found s3s2.difference(s3) # same as s2 - s3</pre>shared between the lists
If we want to see every difference between both setsif __name__ == '__main__': list1 = list(range(1,10)) list2 = list(range(5,15)) print('list1: ', list1) print('list2: ', list2) print('join: ', join_lists(list1, list2)) print('match: ', match_lists(list1, list2)) print('diff: ', diff_lists(list1, we can find the symmetric difference. This will list2))</source>::*The match_lists() function should return a set list that shows contains all numbers that values found in both sets do not share together.lists<pre>s2s3s2 ^ s3 # returns ::*The diff_lists() function should return a set containing list that contains all values that which are not shared between both sets DO NOT sharelistss2.symmetric_difference::*The join_lists(s3) # same function should return a list that contains all values from both lists::*All three functions should accept '''two arguments''' both are lists::*The script should show the exact output as s2 ^ s3the samples::*The script should contain no errors:::'''Sample Run 1:'''<source>./lab4b.pylist1: [1, 2, 3, 4, 5, 6, 7, 8, 9]list2: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]join: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]match: [5, 6, 7, 8, 9]diff: [1, 2, 3, 4, 10, 11, 12, 13, 14]</presource>
Since these powerful features can be so useful :::'''Sample Run 2 (with import) under interactive python shell:'''<source>import lab4blist1 = [1,2,3,4,5]list2 = [2,1,0,-1,-2]print(lab4b.join_lists(list1,list2)))# Will output [0, 1, 2, 3, 4, 5, -2, -1]print(lab4b.match_lists(list1,list2)) # Will output [1, 2]print(lab4b.diff_lists(list1,list2)) # Will output [0, 3, 4, 5, -2, -1]</source>::3. Download the checking script and efficientcheck your work. Enter the following commands from the bash shell.<source lang="bash">cd ~/ops435/lab4/pwd #confirm that you are in the right directoryls CheckLab4.py || wget matrix.senecac.on.ca/~acoatley-willis/CheckLab4.pypython3 ./CheckLab4.py -f -v lab4b</source>::4. Before proceeding, make certain that you identify all errors in lab4b.py. When the checking script tells you may want everything is OK - proceed to try applying them to liststhe next step. == PART 3 - Dictionaries == ::In Python, a '''dictionary''' is a set of key-value pairs. There Dictionaries are some added steps required '''unordered''', like sets, however any value can be retrieved from a dictionary if you want know the key. This section will go over how to create, access, and change dictionaries, giving you a new powerful tool to store and manipulate data. ::'''Perform the Following Steps:'''::#Let's begin by creating a new dictionary in a temporary Python file:<source lang="python">dict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Postal Code': 'M3J3M6'}</source>You should note that the syntax to define a dictionary is similar to defining sets (i.e. using '''{}'''), but unlike sets dictionaries use these functions on lists'''<code>key:value</code>''' pairs within the dictionary, each ''key:value'' pair is separated by commas. First convert ::#All the values in a dictionary can be retrieved by using the '''dictionary.values()''' function. This particular function provides a '''list ''' containing all values:<source lang="python">print(dict_york.values())</source>All keys to access the ''key:pair'' values within a set, perform dictionary can be retrieved using the set comparison or '''dictionary.keys()''' function:<source lang="python">dict_york.keys()</source>We can retrieve <u>individual</u> values from a dictionary by providing the key associated with the value:<source lang="python">print(dict_york['Address'])print(dict_york['Postal Code'])</source>::#Dictionary keys can be any '''immutable''' values (i.e. not permitted for value to be changed). Types of values include: '''strings''', convert '''numbers''', and '''tuples'''.::#Try adding a new key and value to the dictionary:<source lang="python">dict_york['Country'] = 'Canada'print(dict_york)print(dict_york.values())print(dict_york.keys())</source>::#Let's change the province value to BC:<source lang="python">dict_york['Province'] = 'BC'print(dict_york)print(dict_york.values())print(dict_york.keys())</source>'''WARNING: Dictionary keys must be unique'''. Attempting to add a key that already exists in the dictionary will <u>overwrite</u> the set existing value for that key! For example:<source lang="python">dict_york['Province'] = 'ON'print(dict_york)print(dict_york.values())print(dict_york.keys())</source>You should notice that value for the 'Province' key has been changed back to 'ON'.<br><br>The lists that contain the values and keys of the dictionary are not <u>real</u> python lists - they are "views of the dictionary" and therefore are <u>immutable</u>. You could change these views into usable lists by using the '''list()''' function:<source lang="python">list_of_keys = list(dict_york.keys())print(list_of_keys[0])</source>::#Lists can be used with '''for loops''':<source lang="python">list_of_keys = list(dict_york.keys())for key in list_of_keys: print(key)for value in dict_york.values(): print(value)</source> === Create a listPython Script for Managing Dictionaries ===:'''Perform the Following Instructions'''::#Create the '''~/ops435/lab4/lab4c.py''' script. The purpose of this script will be to create dictionaries, extract data from dictionaries, and to make comparisons between dictionaries.::#Use the following as a template:<presource lang="python">l2 #!/usr/bin/env python3 # Dictionariesdict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M3J3M6', 'Province': 'ON'}dict_newnham = {'Address': '1750 Finch Ave E', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M2J2X5', 'Province': 'ON'}# Listslist_keys = [1'Address', 2'City', 3'Country', 4'Postal Code', 5'Province']l3 list_values = [4'70 The Pond Rd', 5'Toronto', 6'Canada', 7'M3J3M6', 8'ON']new_list def create_dictionary(keys, values): # Place code here - refer to function specifics in section below def shared_values(dict1, dict2): # Place code here - refer to function specifics in section below  if __name__ == '__main__': york = listcreate_dictionary(setlist_keys, list_values) print(l2'York: ', york).intersection common = shared_values(setdict_york, dict_newnham) print(l3'Shared Values', common)</source> :::*The script should contain '''two''' functions::::::'''create_dictionary()) # set'''<ol><li>'''accepts''' two lists as arguments keys and values, '''combines''' these lists together to '''create''' a dictionary<br>('''Tip:''' use a while loop to access elements in both the keys and values lists at the same time) can make </li><li>'''returns a dictionary''' that has the keys and associated values from the lists into sets. list</li></ol>:::::'''shared_values() can make ''' <ol><li>'''accepts''' two dictionaries as arguments and '''finds''' all values that are shared between the two dictionaries<br>('''Tip:''' generate sets into containing only values for each dictionary, then use a function mentioned in a previous section to store the values that are common to <u>both</u> lists)</li><li>'''returns a set''' containing '''ONLY values''' found in '''BOTH dictionaries'''</li></ol>:::*make sure the functions have the correct number of arguments required:::*The script should show the exact output as the samples:::*The script should contain no errors::::'''Sample Run 1:'''<source>./lab4c.pyYork: {'Country': 'Canada', 'Postal Code': 'M3J3M6', 'Address': '70 The Pond Rd', 'Province': 'ON', 'City': 'Toronto'}new_listShared Values {'Canada', 'ON', 'Toronto'}</presource>::::'''Sample Run 2 (with import):'''<source>import lab4cdict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M3J3M6', 'Province': 'ON'}dict_newnham = {'Address': '1750 Finch Ave E', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M2J2X5', 'Province': 'ON'}list_keys = ['Address', 'City', 'Country', 'Postal Code', 'Province']list_values = ['70 The Pond Rd', 'Toronto', 'Canada', 'M3J3M6', 'ON'] york = lab4c.create_dictionary(list_keys, list_values)
print(york)
# Will print: {'Address': '70 The Pond Rd',
'City': 'Toronto',
'Country': 'Canada',
'Postal Code': 'M3J3M6',
'Province': 'ON'}
common == Investigation 1 - Part 3 - Dictionary ==lab4c.shared_values(dict_york, dict_newnham)
print(common)# Will print: {'Canada', 'ON', 'Toronto'}</source>:::3. Download the checking script and check your work. Enter the following commands from the bash shell.<source lang== Investigation 1 "bash">cd ~/ops435/lab4/pwd #confirm that you are in the right directoryls CheckLab4.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab4.pypython3 ./CheckLab4.py -f - Part v lab4c</source>:::4 - List Comprehension ==. Before proceeding, make certain that you identify all errors in lab4c.py. When the checking script tells you everything is OK proceed to the next step.
We've already covered lists to = INVESTIGATION 2: STRINGS =:Strings are basically a degree. Lets move into more advanced functions to use and generate listslist of characters (bits of text). This is a very common practice section will investigate strings in Pythonmore detail such as '''cutting strings into sub-strings''', '''joining strings''', understanding how to generate'''formatting strings''', manipulate'''searching through strings''', and apply functions '''matching strings against patterns'''.<br><br>Strings are '''immutable''' data objects - this means that once a string is created, it <u>cannot</u> be modified. In order to items make a change inside a list can be incredibly usefulstring, you would first make a copy of the part of the string (i.e. List comprehension is a way to build new lists from existing listsub-string) for manipulation.
Lets start with creating a list == PART 1 - Strings and applying some function to each item in the list. The below Substrings ==:This first part will print out the square explain basic concepts of each item.<pre>l1 = [1using strings, 2printing strings, 3, 4, 5]for item in l1: print(item ** 2)</pre>and manipulating sub-strings.
If :'''Perform the Following Steps:''':#Create some strings in a temporary Python file:<source lang="python">course_name = 'Open System Automation'course_code = 'OPS435'course_number = 435</source>Strings can contain any '''characters''' inside them, whether they are '''letters''', '''numbers''', or '''symbols'''.:#Strings can also be '''concatenated''' (i.e. "combined together") by using the '''+''' sign, just make sure string are only concatenating strings with strings (no lists, no numbers, no dictionaries, etc.):<source lang="python">print(course_name)print(course_code)print(str(course_number))print(course_name + ' ' + course_code + ' ' + str(course_number))</source>When using the '''print()''' function, you can display '''special characters'''. One such special character is the is the newline character (denoted by the symbol: '''\n'''). This allows you to separate content between new lines or empty lines:<source lang="python">print('Line 1\nLine 2\nLine 3\n')</source>:#Strings have many built-in functions that we would like can use to store these squares manipulate text. [https://docs.python.org/3/library/stdtypes.html#string-methods Here's a list].:#Lets try out several different functions:<source lang="python">print(course_name.lower()) # Returns a string in lower-case lettersprint(course_name.upper()) # Returns a string in upper-case lettersprint(course_name.swapcase()) # Returns a string with upper-case and lower-case letters swappedprint(course_name.title()) # Returns a string with upper-case first letter of each word, lowercase for remaining textprint(course_name.capitalize()) # Returns a string with upper-case first letter only, lowercase for later useremaining text</source>:#These values can be saved inside new strings and then reused:<source lang="python">lower_name = course_name.lower() # Save returned string lower-case string inside new string variableprint(lower_name)</source>:#If a string contains many values separated by a single character, such as a space, we the string can be split on those values and create a new list and append of values<source>lower_name.split(' ') # Provide the squares split() function with a character to it. This split on</source>The above example will generate return a new list that contains squared values in the same positions of strings, which we can access just like all of lists. <br><br>:#Let's practice more string manipulation:<source lang="python">list_of_strings = lower_name.split(' ') # Split string on spaces and store the list in a variableprint(list_of_strings) # Display listprint(list_of_strings[0]) # Display first item in list</source>Since lists are actually a list of '''strings''', you should be able to use any function that works with a string on a list:<source lang="python">list_of_strings[0]. What we are doing upper() # Use the function after the index to affect a single string within a listfirst_word = list_of_strings[0]print(first_word)</source>The '''index''' that is using an existing used to access <u>items</u> within a list , can also be used to access <u>characters</u> within a string. For practice, let's create a new list.string, and start accessing the strings index:<source>course_name = 'Open System Automation'course_code = 'OPS435'course_number = 435print(course_code[0]) # Print the first character in course_codeprint(course_code[2]) # Print the third character in course_codeprint(course_code[-1]) # Print the last character in course_codeprint(str(course_number)[0]) # Turn the integer into a string, return first character in that string, and print itprint(course_code[0] + course_code[1] + course_code[2])<pre/source>l1 :#You can use a technique that uses index numbers of a string to '''cut-out''' or '''"parse"''' smaller portions of text within a string. This term is referred to as a '''substring'''. We can use this to create a new string or display only a small portion of it:<source lang= "python">print(course_name[0:4]) # Print the first four characters (values of index numbers 0,1, 2, and 3) first_word = course_name[0:4] # Save this substring for later useprint(course_code[0:3]) # Print the first three characters (values of index numbers 0, 41, and 2)</source>:# The index allows a few '''extra functions''' using the same parsing technique:<source lang="python">course_name = 'Open System Automation'print(course_name[12:]) # Print the substring '12' index until end of stringprint(course_name[5:]) # Print the substring '5' index until end of stringprint(course_name[-1]) # Print the last characterl2 </source>With '''negative indices''', '''-1''' would represent the '''last''' character, '''-2''' index would represent the '''second last''' character, etc.:<source lang= "python">course_name = 'Open System Automation'print(course_name[-1])for item print(course_name[-2])</source>:# Practice some of the skills that you have learned in l1this section:<source>course_name = 'Open System Automation' l2.appendprint(course_name[-10:]) # Return the last ten charactersprint(course_name[-10:-6]) # Try and figure out what this is returning print(item ** 2course_name[0:4] + course_name[-10:-6]) # Combine substrings togetherl1substring = course_name[0:4] + course_name[-10:-6] # Save the combined substring as a new string for laterl2print(substring)</presource>:# The real power found in substrings goes beyond just manually writing index values and getting back words. The next part of this investigation will cover how to search through a string for a specific word, letter, number, and return the index to that search result.
Lets take another step here'''Create a Python Script Demostrating Substrings''':'''Perform the Following Instructions''':#Create the '''~/ops435/lab4/lab4d. Lets move the squaring of numbers out into itpy'''s own separate functionscript. While the squaring example The purpose of this script is a simple function, this example could include a more complex to demonstrate creating and manipulating strings. There will be four functions that does each will return a lot more processing on each item in the listsingle string.:#Use the following template to get started:<presource>def square(number):#!/usr/bin/env python3 return number ** 2# Strings 1
l1 str1 = [1, 2, 3, 4, 5]'Hello World!!'l2 str2 = []for item in l1: l2.append(square(item))'Seneca College'
l1num1 = 1500l2</pre>num2 = 1.50
def first_five():
# Place code here - refer to function specifics in section below
The map function can be used to apply a function on each item in a list. This is exactly what we did above, however it gives us much better syntax, removes the loop, including the variable we had to create to do the loop. This will make our work a little more efficient while performing the same task.<pre>def squarelast_seven(number): return number ** 2# Place code here - refer to function specifics in section below
l1 = [1,2,3,4,5]l2 = list(mapdef middle_number(square, l1)): # Place code here - refer to function specifics in section below
l1def first_three_last_three():l2</pre> # Place code here - refer to function specifics in section below
The above map function required us to provide it with a function, and a list. This meant that before we could use map we needed to define a function earlier in the script. We can avoid this entire function definition through the use of anonymous functions. This is the ability to create a simple function without defining it, and pass it off for use. Below we will use lambda, which will return a function, and we can use that function immediately. The function takes 1 argument x, and it will perform a single operation on x, square it.
<pre>
square = lambda x: x ** 2
l1 = [1,2,3,4,5]
l2 = list(map(square, l1))
l1if __name__ == '__main__':l2 print(first_five(str1)) print(first_five(str2)) print(last_seven(str1)) print(last_seven(str2)) print(middle_number(num1)) print(middle_number(num2)) print(first_three_last_three(str1, str2)) print(first_three_last_three(str2, str1))</presource>
::*The above code is actually not particularly good, script should contain '''four''' functions (use your own argument names):::::'''first_five()''':<ol><li>Accepts a single string argument</li><li>Returns a string that contains the whole purpose first five characters of using lambda here is we were avoiding the function definition and just quickly returning argument given</li></ol>::::'''last_seven()''':<ol><li>Accepts a function. However this does break down exactly what lambda does, it returns single string argument</li><li>Returns a function for use. Lets fix this and remove string that contains the square function and just use last seven characters of the return function from lambda. Now remember what map requires? mapargument given</li></ol>::::'''middle_number()'''s first :<ol><li>Accepts a integer as a argument is </li><li>Returns a function, string containing the second and mapthird characters in the number</li></ol>::::'''first_three_last_three()'''s second argument is :<ol><li>Accepts two string arguments</li><li>Returns a list. Here lambda will return a function single string that starts with the first three characters of argument1 and provide it as ends with the first argument.last three characters of argument2</li></ol>::*Example: first_three_last_three('abcdefg', '1234567') returns single string 'abc567':::'''Sample Run 1'''<presource>l1 = [1,2,3,4,./lab4d.py HelloSenecWorld!!College50.5]l2 = list(map(lambda xHelegeSend!!</source>::: x ** '''Sample Run 2, l1)(with import)'''<source>import lab4d
l1str1 = 'Hello World!!'l2str2 = 'Seneca College'</pre>num1 = 1500num2 = 1.50
print(lab4d.first_five(str1))
# Will output 'Hello'
print(lab4d.first_five(str2))
# Will output 'Senec'
print(lab4d.last_seven(str1))
# Will output 'World!!'
print(lab4d.last_seven(str2))
# Will output 'College'
print(lab4d.middle_number(num1))
# Will output '50'
print(lab4d.middle_number(num2))
# Will output '.5'
print(lab4d.first_three_last_three(str1, str2))
# Will output 'Helege'
print(lab4d.first_three_last_three(str2, str1))
# Will output 'Send!!'
</source>
::3. Download the checking script and check your work. Enter the following commands from the bash shell.<source>
cd ~/ops435/lab4/
pwd #confirm that you are in the right directory
ls CheckLab4.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab4.py
python3 ./CheckLab4.py -f -v lab4d
</source>
::4. Before proceeding, make certain that you identify all errors in lab4d.py. When the checking script tells you everything is OK - proceed to the next step.
= Investigation 2 LAB 4 SIGN- Strings OFF (SHOW INSTRUCTOR) =Strings are [[Image:lab1_signoff.png|thumb|right|450px|Students should be prepared with '''all required commands (system information) displayed in their most basic form a list of characters, terminal (or a bit of text. Strings store text so that we can use them later. In this section we will cover more than just displaying that text multiple terminals) prior to calling the screen. Here, we will go over cutting strings into sub-strings, joining strings together, searching through strings, and matching strings against patternsinstructor for signoff'''.]]
== Investigation 2 - Part 1 - String Basics ==
We can concatenate strings using the plus sign. Combining strings together to create a brand new string, strings are immutable just like tuples. This means everytime you change a string, you are actually creating a new string.<pre>str1 = :'Paul'str2 = 'AtreidesHave Ready to Show Your Instructor:'str3 = str1 + ' ' + str2str3</pre>
Repetition is also a useful tool that can be used with strings::<span style="color:green;font-size:1. Repetition repeats the string over and over a specific amount 5em;">&#x2713;</span> Output of times: <code>. This is useful anytime you would manually be typing the same thing over again/CheckLab4.py -f -v<pre/code>str1 ::<span style= 'Paul'str2 = 'Atreides'str3 = str1 + ' ' + str2 + ' ' + 'I'str3str3 = str1 + ' ' + str2 + ' ' + 'I'*3str3"color:green;font-size:1.5em;">&#x2713;</span> Output of: <code>cat lab4a.py lab4b.py lab4c.py lab4d.py</precode>
= LAB REVIEW =
# What is the purpose of a '''tuple'''? How does a tuple differ from a list?
# How do you define elements within a tuple?
# Write Python code to confirm if the string ''''OPS435'''' exists within the tuple called '''courses'''.
# What is the purpose of a '''set'''? How do sets differ from lists or tuples?
# How do you define elements within a set?
# Assuming you have defined two sets called '''set1''' and '''set2'''. Write Python code to:<ol type="a"><li>Return a set containing all values of both sets</li><li>Returns a set containing all values in set1 that are not found in set2</li><li>Return a set containing all values that both sets DO NOT share</li></ol>
# What is the purpose of a dictionary?
# How do you define elements within a dictionary?
# Write Python commands to display for a dictionary called '''my_dictionary''' the dictionary key called '''my_key''' and a dictionary value for that key?
# What is the purpose for the '''range()''', '''len()''', '''append()''', and '''map()''' functions for a dictionary?
# List and briefly explain the following functions (methods) that can be used with strings:<br>'''lower()''' , '''upper()''' , '''swapcase()''' , '''title()''' , '''captilize()''' , '''split()'''
# Assume you issued the following command in your ipython3 shell:<br>'''course_name = 'Programming with Python''''<br>What will be the output for each of the following Python commands?<ol type="a"><li>'''course_name[3:11]'''</li><li>'''course_name[10:]'''</li><li>'''course_name[-1]</li></ol>
== Investigation 2 [[Category:OPS435- Part 1 - String Manipulation ==== Investigation 2 - Part 1 - Regular Expressions ==Python]]
1,760
edits

Navigation menu