Format Expression and Format Method

Format Expression and Format Method

There are two ways to format strings. The first is the Expression (which it's character is known for as %) and the second is the newer technique: the format method str.format().

Format Expressions

The % operator when applied to strings provides a way to format a string according to it's format definition. The way it is applied is like so:

When you plug in more than two values into the string they need to be within parenthesis. The %i gets replaced by the integer 2 and the %s gets replaced by string 'ways'. If you do not input the correct definition for the corresponding value you will get an error. The below code shows an example of attempting to input two integers where one of them is a string.

The string table shows the various definitions under the String tab.

Format Method

Unlike the format expressions, you can use the format method to plug in any data to a string without specifying it's definition.

As you can see. The type of data it is, does not matter. Here, the {} indicate the definition of whatever is in the order of the format()'s arguments. By default empty curly brackets {} plug format()'s arguments into the string at their position they are in format(). You can also change this order of postion.

You can also plug the values in by keyword.

Or you can do them both by position and keyword.



Specific Formatiing

Yes. It can get more complicated. The format for {} inside a string is: {fieldname!convertionflag:formatspec}
Fieldname is a number or keyword naming an argument, followed by optional ".name" attribute or "[index]" component references.
Conversionflag can be r, s, or a to call repr, str, or ascii built in functions on the value.
Formatspec specifies how the value should be presented (width, alignment, padding, decimal precision, etc.) Within the formatspec a subcategory of: [[fill]align][sign][#][0][width][.precision][typecode] gives the specifications of how it should be presented. Align can be <, >, =, or ^, for the left alignment, right alignment, padding after a sign character, or centered alignment. The formatspec also contains a nested {} format strings with field name only.