OPS435 Python Extra Advanced String formatting
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: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 ( ).
ipython3
- To demonstrate using the format() function, issue the following:
print( 'College is Great'.format() )
- The above example does not actualy do any formatting, next add a string using the format() function argumentsWhen 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
print('College is {}'.format('Great'))
- To demonstrate, issue the following: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.
print('{} {} {}'.format('a', 'b', 'c'))
- To demonstrate by creating too many braces, issue the following:For situations like above, if reusing strings more than once is important, positional values can be placed inside the curly braces.
print('{} {} {} {}'.format('a', 'b', 'c'))
- Issue the following to see what happens:These positions make formating each string much less prone to errors while also making the string being formatted much more clear.
print('{0} {1} {1} {2}'.format('a', 'b', 'c')) print('{2} {2} {1} {0}'.format('a', 'b', 'c'))
- To improve on formatting further, issue the following to provide the format() function with string variables:The format() function by default tries to use values as strings, all values is {} are displayed as strings unless extra options are given.
course_name = 'Open System Automation' course_code = 'OPS435' print('{0} {1} {0}'.format(course_code, course_name))
- Issue the following:Next, let's place a list inside the format() function and access the values, there are two ways to use the list.
course_number = 435 # This is an integer print('This is displaying a string by default: {0}'.format(course_number))
- Let's demonstrate a range of alternative methods of printing a list by issuing the following:Let's now place a dictionary inside the format() functions and access the values, again there are a few ways to use the dictionary
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
- Issue the following:With dictionaries however, instead of using positional arguments 0 each access to a key, python allows for expansion of keyword arguments.
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]}
- 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!'))
- Variables may also be passed to these keyword arguments: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.
college = 'Seneca College' print('{string1} is {string2} {string2}'.format(string1=college, string2='Great!'))
- 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'))
- Start the ipython3 shell: