Introduction to Python

advertisement
Introducing Python
CS 4320, SPRING 2015
Format: Field widths and Alignment
The string representation of a value can be padded out to a specific width with spaces
This will make neat columns of data when printed
The desired number of characters is specified by including a colon in the replacement field, right after
the parameter index if it is included: {2:10} or {:10}
◦ Following the colon is the number of total characters the value is to take
If the value takes more than the specified number of characters when first converted, no padding is
done
◦ This will cause columns to not align properly, but no data is lost
An alignment character can appear between the colon and the width
◦ < forces left alignment {2:<10}
◦ > forces right alignment {2:>10}
◦ ^ forces centering {2:^10}
1/7/2015
CS 4320, SPRING 2015
2
Format: Decimal Places
For floating point numbers, the format can specify the exact number of decimal places to display
The value displayed is rounded from the internal value
To specify decimal places, put a decimal point following the field width, or directly following the
colon if there is not field width specified
After the decimal point, put the number of decimal places desire
Follow this with the letter ‘f’ (must be lower case)
Note: the number of decimal places is not added to the field width, it is part of the total field
width
◦ {:10.3f} will use 10 characters total. Of these, one will be a decimal point and 3 will be for decimal
places. That leaves six characters for the integer part and a possible negative sign
1/7/2015
CS 4320, SPRING 2015
3
Comments About Formatting
The Format String Syntax section of the Python library documentation gives details about many
other options and possibilities
There is a built-in function format that can be used for single values. This can be helpful with
web pages since creating columns is done with tags in HTML rather than spacing
Do not attempt to format floating point values by using rounding functions.
◦ This will often lose precision in calculations, which is not desirable
◦ The rounded value will not always display with the expected number of decimal points because of the
way floating point arithmetic is carried out
1/7/2015
CS 4320, SPRING 2015
4
Download