Open main menu

CDOT Wiki β

OPS435 Python Extra Advanced String formatting

Revision as of 13:18, 1 September 2017 by Oatley (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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:
  1. Start the ipython3 shell:
    ipython3
    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 ( ).

  2. To demonstrate using the format() function, issue the following:
    print( 'College is Great'.format() )
  3. The above example does not actualy do any formatting, next add a string using the format() function arguments
    print('College is {}'.format('Great'))
    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

  4. To demonstrate, issue the following:
    print('{} {} {}'.format('a', 'b', 'c'))
    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.

  5. To demonstrate by creating too many braces, issue the following:
    print('{} {} {} {}'.format('a', 'b', 'c'))
    For situations like above, if reusing strings more than once is important, positional values can be placed inside the curly braces.

  6. Issue the following to see what happens:
    print('{0} {1} {1} {2}'.format('a', 'b', 'c'))
    print('{2} {2} {1} {0}'.format('a', 'b', 'c'))
    These positions make formating each string much less prone to errors while also making the string being formatted much more clear.

  7. To improve on formatting further, issue the following to provide the format() function with string variables:
    course_name = 'Open System Automation'
    course_code = 'OPS435'
    print('{0} {1} {0}'.format(course_code, course_name))
    The format() function by default tries to use values as strings, all values is {} are displayed as strings unless extra options are given.

  8. Issue the following:
    course_number = 435             # This is an integer
    print('This is displaying a string by default: {0}'.format(course_number))
    Next, let's place a list inside the format() function and access the values, there are two ways to use the list.

  9. Let's demonstrate a range of alternative methods of printing a list by issuing the following:
    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
    Let's now place a dictionary inside the format() functions and access the values, again there are a few ways to use the dictionary

  10. Issue the following:
    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]}
    With dictionaries however, instead of using positional arguments 0 each access to a key, python allows for expansion of keyword arguments.

  11. 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:
    print('{string1} is {string2} {string2}'.format(string1='College', string2='Great!'))
  12. Variables may also be passed to these keyword arguments:
    college = 'Seneca College'
    print('{string1} is {string2} {string2}'.format(string1=college, string2='Great!'))
    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.

  13. Let's try this below. Pay close attention to the keys inside the dictionary and the values associated with each key:
    # 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'))