6 Formatting Strings
6 Formatting Strings
Formatting Strings
The syntax for formatting strings is a little cryptic at times, but once you get used to it, it not too bad, and it is quite useful. The method that Python uses to format strings is similar to that of Java, C and C++. To format a string we separate the way our variables are to be displayed from the actual values, then the values get inserted the way we want them. e.g.
name = Bob bill = 45.1 print Hi %s, your bill comes to $%.2f % (name, bill)
String Formatting Syntax: <format string> % <values> <format string> - in this example Hi %s, your bill comes to $%.2f. Most of the string is displayed exactly as we type it. %s and %.2f are called conversion specifiers. When we run this line the conversion specifiers are replaced by values from the value list (in order) and displayed as specified. <conversion specifiers> - A conversion specifier always starts with a %, and you need to specify what type of value you want to display. %s - string %i - integer %f - float You can also specify options about how you want the value displayed, like - how big of a field to display the value in. - how many decimal places for float values - whether the value should be left-aligned or right-aligned. Field spacing The field spacing is the total number of spaces used to display your value, including the ones used by your value. e.g.
a = 12.3456 n = 300 s = Ching %10f %10s %10i %10.2f %-10.2f %2i
- note the decimal takes up one space - note that it will round off - - will left align - making the field smaller than the number of characters will not chop off characters