Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 4

352 bytes added, 09:20, 23 June 2017
PART 3 - String Formatting Advanced Features
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 using '''{:f}''' ,<br> use '''{:d}''' for decimal '''INTEGERS'''.<br><br>:#To demonstrate, issue the following:<source>
print('{0:d}'.format(number1))
print('{0:d}'.format(number2))
print('{0:+d}'.format(number1))
print('{0:+d}'.format(number2))
</source>'''NOTE:#''' When using '''{:d}''' be careful not to use numbers with a decimal value in them, the following will create a error<br><br>:#Issue the following to see the difference:<source>
number3 = 1.50
print('{0:d}'.format(number3))
</source>:#Next lets , let's move on to allignment of aligning '''strings''' (text). This is the process of adding padding to the left of our text, the right of our text, or aligning to the centreor our text (i.e. padding both left and right). Through the alignment the text field size of , any string can be setto allow it to fit within a column (or columns), and make it easier for the user to read data. <br><br>:#Start by using a string but placeing a number value after the colon '''{0:10}'''by issuing:<source>
string1 = 'hello'
string2 = 'world'
13,420
edits