Changes

Jump to: navigation, search

OPS435 Python Extra Advanced String formatting

5,696 bytes added, 14:18, 1 September 2017
Created page with "= INVESTIGATION 1: Advanced String Formatting = == PART 2 - String Formatting Basic Fundamentals== :In Python scripting, using plus signs and commas for string concatenation..."
= INVESTIGATION 1: Advanced String Formatting =
== PART 2 - String Formatting Basic Fundamentals==

:In Python scripting, using plus signs and commas for string concatenation is very limited and can become messy when when used at length with many values and/or calculations. This section will cover the '''format()''' function that can be used with every type of string. This function allows the user of Python to create well formatted code, to align text, and to convert values efficiently and cleanly. While this section uses lists and dictionaries, they contain strings which can be accessed and displayed in a formatted manner.

:'''Perform the Following Steps:'''
:#Start the ipython3 shell:<source>
ipython3
</source>To start, let's use the '''format()''' function on a string, The text '''.format()''' is located at the end of a defined string. The ''format()'' function can contain arguments or parameters within the parenthesis ( ).<br><br>
:#To demonstrate using the ''format()'' function, issue the following:<source>
print( 'College is Great'.format() )
</source>
:#The above example does not actualy do any formatting, next add a string using the format() function arguments<source>
print('College is {}'.format('Great'))
</source>When the format function reads '''{}''' curly braces, it performs special actions. For example, if format() finds '''{}''' with nothing inside it substitutes the string from it's arguments. These arguments are done by position left to right<br><br>
:#To demonstrate, issue the following:<source>
print('{} {} {}'.format('a', 'b', 'c'))
</source>However, using this method while quick, easy, and clean has a issue. If more curly braces '''{}''' are in the string than in the format() arguments, it will create an '''error'''.<br><br>
:#To demonstrate by creating too many braces, issue the following:<source>
print('{} {} {} {}'.format('a', 'b', 'c'))
</source>For situations like above, if reusing strings more than once is important, '''positional values''' can be placed inside the curly braces.<br><br>
:#Issue the following to see what happens:<source>
print('{0} {1} {1} {2}'.format('a', 'b', 'c'))
print('{2} {2} {1} {0}'.format('a', 'b', 'c'))
</source>These positions make formating each string much less prone to errors while also making the string being formatted much more clear.<br><br>
:#To improve on formatting further, issue the following to provide the format() function with string variables:<source>
course_name = 'Open System Automation'
course_code = 'OPS435'
print('{0} {1} {0}'.format(course_code, course_name))
</source>The format() function by default tries to use values as strings, all values is '''{}''' are displayed as strings unless extra options are given.<br><br>
:#Issue the following:<source>
course_number = 435 # This is an integer
print('This is displaying a string by default: {0}'.format(course_number))
</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 a range of alternative methods of printing a list by issuing the following:<source>
list1 = [1,2,3,4,5] # This is a list of numbers
print('{0[0]} {0[1]} {0[2]} {0[3]} {0[4]}'.format(list1)) # Access the values of the list via {position[index]}
print('{0} {1} {2} {3} {4}'.format(*list1)) # Expand the list into multiple positional arguments
print('{} {} {} {} {}'.format(*list1)) # Expand the list into multiple positional arguments
print('{0} {1} {2} {3} {4}'.format(1,2,3,4,5)) # Same results as above
</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 entire dictionary
print('{0}'.format(dict_york)) # Print entire dictionary using format arguments position
print('{0[City]} {0[Country]}'.format(dict_york)) # Print 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>
print('{string1} is {string2} {string2}'.format(string1='College', string2='Great!'))
</source>
:#Variables may also be passed to these keyword arguments:<source>
college = 'Seneca College'
print('{string1} is {string2} {string2}'.format(string1=college, string2='Great!'))
</source>Now back to dictionaries. Using keyword arguments(sometimes referred to as '''kwargs''' in python). The dictionary can be quickly and easily expanded into these keyword arguments using the syntax '''**dictionary_name'''.<br><br>
:#Let's try this below. Pay close attention to the keys inside the dictionary and the values associated with each key:<source>
# Define a dictionary:
dict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Country': 'Canada', 'Postal Code': 'M3J3M6', 'Province': 'ON'}
# Uses the dictionary's keyword arguments:
print('{City} {Province} {Country}'.format(**dict_york))
# Creates new keyword arguments:
print('{City} {Province} {Country}'.format(City='Toronto', Province='ON', Country='Canada'))
</source>
198
edits

Navigation menu