Changes

Jump to: navigation, search

OPS435 Python Lab 4

152 bytes added, 19:06, 21 June 2017
PART 2 - String Formatting
:#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 finds function reads '''{}''' curly braces, it performs special actions. If 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 positional method while quick, easy, and clean has a issue, if . If more curly braces '''{}''' are in the string than in the format() arguments, it will create a error. This next string is going to throw a 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'))
13,420
edits

Navigation menu