Changes

Jump to: navigation, search

OPS435 Python Lab 4

165 bytes removed, 19:19, 21 June 2017
PART 2 - String Formatting
</source>Next, let's place a list inside the format() function and access the values, there are two ways to use the list.<br><br>
:#Let's demonstrate by issuing the following:<source>
list1 = [1,2,3,4,5] # While this This is a list of numbers, format() by default tried to print everything as a str()print('{0[0]} {0[1]} {0[2]} {0[3]} {0[4]}'.format(list1)) # Access the values of the list using indexes via {position[index]} print('{0} {1} {2} {3} {4}'.format(*list1)) # Use *list1 to expand Expand the list into multiple positional arguments for format()print('{} {} {} {} {}'.format(*list1)) # Use *list1 to expand Expand the list into multiple positional arguments for format()print('{0} {1} {2} {3} {4}'.format(1,2,3,4,5)) # Use *list1 in this situation is the same Same results as thisabove
</source>Let's now place a dictionary inside the format() functions and access the values, again there are a few ways to use the dictionary<br><br>
:#Issue the following:<source>
dict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M3J3M6', 'Province': 'ON'}
print('{}'.format(dict_york)) # Print out whole entire dictionaryprint('{0}'.format(dict_york)) # Print out whole entire dictionary using format arguments positionprint('{0[City]} {0[Country]}'.format(dict_york)) # Print out values using position and key {position[key]}
</source>With dictionaries however, instead of using positional arguments '''0''' each access to a key, python allows for expansion of keyword arguments.<br><br>
:#Let's take a look at the example of a keyword arguments, place the keyword variable name in between '''{}''' and add the keyword argument to the format() function:<source>
13,420
edits

Navigation menu