Changes

Jump to: navigation, search

OPS435 Python Lab 4

129 bytes added, 09:13, 23 June 2017
PART 3 - String Formatting Advanced Features
print('{0:f}'.format(number2)) # A colon separate the position/index areas from the extra functionality
print('{0:f}'.format(number3)) # "f" represents the fixed point number
</source>Notice that there are many decimal places after this number. This makes the number look "ugly". We need to further format the number to indicate the number of decimal places (or no decimal places if number is an integer). A fixed point number means that it can control the number of digits that come after the decimal point, try changing the '''.2''' to any other number and experiment.<br><br>
:#Issue the following to demonstrate:<source>
print('{0:.0f}'.format(number1)) # Show no digits after decimal point
print('{0:.1f}'.format(number3)) # Show one digit after decimal point
</source>
:#Numbers can be displayed with the '''-''' or '''+''' signs before the digits, this could be important in formatting. Issue the following to demonstrate:<source>
print('{0: f}'.format(number1)) # Show a space where plus sign should be
print('{0: f}'.format(number2)) # Shows negative sign normally
print('{0: f}\n{1: f}'.format(number1, number2)) # The space before the f lines up positive and negative numbers
</source>
:#Placing a '''+''' before the f changes the format so that plus signs show up for positive numbers and negative signs show up for negative numbers. Try issuing the following:<source>
print('{0:+f}'.format(number1)) # Show a space where plus sign should be
print('{0:+f}'.format(number2)) # Shows negative sign normally
print('{0:+f}\n{1:+f}'.format(number1, number2)) # The space before the f lines up positive and negative numbers
</source>
:#Combining fixed point positions and sign together look like the followingby issuing:<source>
print('{0:+.2f}'.format(number1))
print('{0:+.2f}'.format(number2))
print('{0:+.2f}\n{1:+.2f}'.format(number1, number2))
</source>:#In the event that the numbers being shown are all integers and do no require the decimal values, instead of '''{:f}''' use '''{:d}''' for decimal INTEGERS<br><br>:#To demonstrate, issue the following:<source>
print('{0:d}'.format(number1))
print('{0:d}'.format(number2))
13,420
edits

Navigation menu