Встроенные функции

String format()

The method allows you to format selected parts of a string.

Sometimes there are parts of a text that you do not control, maybe
they come from a database, or user input?

To control such values,
add placeholders (curly brackets ) in the text, and run the values through the
method:

Example

Add a placeholder where you want to display the price:

price = 49txt = «The price is {} dollars»print(txt.format(price))

You can add parameters inside the curly brackets to specify how to convert
the value:

Example

Format the price to be displayed as a number with two decimals:

txt = «The price is {:.2f} dollars»

Check out all formatting types in our String format() Reference.

Reordering Formatters with Positional and Keyword Arguments

When we leave curly braces empty without any parameters, Python will replace the values passed through the method in order. As we have seen, so far, a formatter construction with two empty curly braces with two values passed through will look like this:

The first pair of curly braces is substituted with the string value of , and the second pair is substituted with the string value of .

The values that exist within the method look like this:

They are essentially the tuple data type and each individual value contained in the tuple can be called by its index number, which starts with the index number 0.

We can pass these index numbers into the curly braces that serve as the placeholders in the original string:

In the above example, the output will be what we get without passing index numbers into the braces as we are calling the values in the tuple in order:

But, if we reverse the index numbers with the parameters of the placeholders we can reverse the values being passed into the string:

If you call an index number of 2 in a tuple that has values at index positions 0 and 1, then you are calling on a value that is out of range. When you call an index number that is out of range, you’ll receive an error message:

The error message we see refers to the tuple only having values at index numbers 0 and 1, therefore placing index number 2 out of range.

Let’s add a few more placeholders and a few more values to pass to them, so we can understand how we can reorder formatters a little better. First, here is a new string with four placeholders:

Without parameters, the values that are passed into the method are concatenated into the string in order.

The string values contained in the tuple correspond to the following index numbers:

“happy” “smiling” “blue” “shark”
1 2 3

Let’s use the index numbers of the values to change the order that they appear in the string:

Since we started with index number 3, we called the last value of first. The other index numbers included as parameters change the order of how the words appear within the original string.

In addition to positional arguments, we can also introduce keyword arguments that are called by their keyword name:

This example shows the use of a keyword argument being used with positional arguments. We can fill in the keyword argument alongside positional arguments, and can move these arguments around to change the resulting string:

Positional and keyword arguments used with string formatters give us more control over manipulating our original strings through reordering.

Formatter Methods

The Formatter class takes no initialization arguments:

fmt = Formatter()

The public API methods of class Formatter are as follows:

-- format(format_string, *args, **kwargs)
-- vformat(format_string, args, kwargs)

‘format’ is the primary API method. It takes a format template,
and an arbitrary set of positional and keyword arguments.
‘format’ is just a wrapper that calls ‘vformat’.

‘vformat’ is the function that does the actual work of formatting. It
is exposed as a separate function for cases where you want to pass in
a predefined dictionary of arguments, rather than unpacking and
repacking the dictionary as individual arguments using the *args and
**kwds syntax. ‘vformat’ does the work of breaking up the format
template string into character data and replacement fields. It calls
the ‘get_positional’ and ‘get_index’ methods as appropriate (described
below.)

Formatter defines the following overridable methods:

-- get_value(key, args, kwargs)
-- check_unused_args(used_args, args, kwargs)
-- format_field(value, format_spec)

‘get_value’ is used to retrieve a given field value. The ‘key’ argument
will be either an integer or a string. If it is an integer, it represents
the index of the positional argument in ‘args’; If it is a string, then
it represents a named argument in ‘kwargs’.

The ‘args’ parameter is set to the list of positional arguments to
‘vformat’, and the ‘kwargs’ parameter is set to the dictionary of
positional arguments.

For compound field names, these functions are only called for the
first component of the field name; subsequent components are handled
through normal attribute and indexing operations.

So for example, the field expression ‘0.name’ would cause ‘get_value’
to be called with a ‘key’ argument of 0. The ‘name’ attribute will be
looked up after ‘get_value’ returns by calling the built-in ‘getattr’
function.

If the index or keyword refers to an item that does not exist, then an
IndexError/KeyError should be raised.

‘check_unused_args’ is used to implement checking for unused arguments
if desired. The arguments to this function is the set of all argument
keys that were actually referred to in the format string (integers for
positional arguments, and strings for named arguments), and a reference
to the args and kwargs that was passed to vformat. The set of unused
args can be calculated from these parameters. ‘check_unused_args’
is assumed to throw an exception if the check fails.

‘format_field’ simply calls the global ‘format’ built-in. The method
is provided so that subclasses can override it.

To get a better understanding of how these functions relate to each
other, here is pseudocode that explains the general operation of
vformat:

def vformat(format_string, args, kwargs):

  # Output buffer and set of used args
  buffer = StringIO.StringIO()
  used_args = set()

  # Tokens are either format fields or literal strings
  for token in self.parse(format_string):
    if is_format_field(token):
      # Split the token into field value and format spec
      field_spec, _, format_spec = token.partition(":")

      # Check for explicit type conversion
      explicit, _, field_spec  = field_spec.rpartition("!")

      # 'first_part' is the part before the first '.' or ' or .subfield. Assume that 'components'
      # returns an iterator of the various subfields, not including
      # the first part.
      for comp in components(field_spec):
        value = resolve_subfield(value, comp)

      # Handle explicit type conversion
      if explicit == 'r':
        value = repr(value)
      elif explicit == 's':
        value = str(value)

      # Call the global 'format' function and write out the converted
      # value.
      buffer.write(self.format_field(value, format_spec))

    else:
      buffer.write(token)

  self.check_unused_args(used_args, args, kwargs)
  return buffer.getvalue()

Using Formatters

Formatters work by putting in one or more replacement fields or placeholders — defined by a pair of curly braces — into a string and calling the method. You’ll pass into the method the value you want to concatenate with the string. This value will be passed through in the same place that your placeholder is positioned when you run the program.

Let’s print out a string that uses a formatter:

In the example above, we constructed a string with a pair of curly braces as a placeholder:

We then added the method and passed the value of the integer to that method. This places the value of into the string where the curly braces were:

We can also assign a variable to be equal to the value of a string that has formatter placeholders:

In this second example, we concatenated the string with the larger string, replacing the curly braces in the original string.

Formatters in Python allow you to use curly braces as placeholders for values that you’ll pass through with the method.

Differences between f-string and str.format expressions

There is one small difference between the limited expressions allowed
in str.format() and the full expressions allowed inside
f-strings. The difference is in how index lookups are performed. In
str.format(), index values that do not look like numbers are
converted to strings:

>>> d = {'a': 10, 'b': 20}
>>> 'a={d}'.format(d=d)
'a=10'

Notice that the index value is converted to the string 'a' when it
is looked up in the dict.

However, in f-strings, you would need to use a literal for the value
of 'a':

>>> f'a={d}'
'a=10'

This difference is required because otherwise you would not be able to
use variables as index values:

>>> a = 'b'
>>> f'a={d}'
'a=20'

See for a further discussion. It was this observation that led to
full Python expressions being supported in f-strings.

Furthermore, the limited expressions that str.format() understands
need not be valid Python expressions. For example:

>>> '{i}'.format(i={'";':4})
'4'

String Methods

The built-in string class (and also the unicode class in 2.6) will
gain a new method, ‘format’, which takes an arbitrary number of
positional and keyword arguments:

"The story of {0}, {1}, and {c}".format(a, b, c=d)

Within a format string, each positional argument is identified
with a number, starting from zero, so in the above example, ‘a’ is
argument 0 and ‘b’ is argument 1. Each keyword argument is
identified by its keyword name, so in the above example, ‘c’ is
used to refer to the third argument.

There is also a global built-in function, ‘format’ which formats
a single value:

print(format(10.0, "7.3g"))

No use of globals() or locals()

In the discussions on python-dev , a number of solutions where
presented that used locals() and globals() or their equivalents. All
of these have various problems. Among these are referencing variables
that are not otherwise used in a closure. Consider:

>>> def outer(x):
...     def inner():
...         return 'x={x}'.format_map(locals())
...     return inner
...
>>> outer(42)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in inner
KeyError: 'x'

This returns an error because the compiler has not added a reference
to x inside the closure. You need to manually add a reference to x in
order for this to work:

>>> def outer(x):
...     def inner():
...         x
...         return 'x={x}'.format_map(locals())
...     return inner
...
>>> outer(42)()
'x=42'

In addition, using locals() or globals() introduces an information
leak. A called routine that has access to the callers locals() or
globals() has access to far more information than needed to do the
string interpolation.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *