Three methods python format string (%, format, f-string)

DAY 7. formatted string

So far I know, there are three ways python format string, first there is the early percent, followed by the format after the 2.5 (), there is added 3.6 f string debugging

7.1% formatted string

% Python format string is the earliest, and it is compatible with all versions of string formatting method, in some python library earlier recommended% formatted the way, he would string formatting by character Alternatively after the parameter sequence, the format

"xxxxxx %s xxxxxx" % (value1, value2)
  • Wherein %sit is formatted character, meaning that the value of the back of the character type format, as well as similar character format %d, %fand the like, with particular reference to articles Python string formatted
  • Later value1, value2it is to be formatted values, whether numerical or character, will be formatted as a character corresponding to the type of formatted
  • Of course, you can not pass a value in the form of a tuple, you can directly write this: "xxxxx %s" % valuebut do not propose to write, one should only pass a parameter to this, and second, if the value is a tuple or list such as type, this will trigger TypeErrer
  • If you only pass a parameter, and it will not trigger an exception to determine the parameter type, you can use the above wording, otherwise, I recommend that you provide a tuple, just like"xxxx %s " % (value,)
value1 = (7, 8)
value2 = [9, 0]
print("DAY %s 格式化字符串 %s " % (value1,value2))
value3 = 1
s = "xxxix %s" % value3  # 不推荐
print(s)
s1 = "xxxx %s " % value1
print(s1)  # TypeError: not all arguments converted during string formatting

7.2 format()

%, While powerful, but inevitably some trouble with it, the code is not particularly beautiful, and therefore, after the python 2.5, provides a more elegant str.format()method.

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass
  • format () of common usage
# 使用名称占位符
s2 = "xxxx {age} xxxx {name}".format(age=18, name="hangman")
print(s2)  # xxxx 18 xxxx hangman

# 使用序号占位符,为空默认从左到右01234.。。
s3 = "xxxx {1} xxx{0}".format(value1,value2)
print(s3)  # xxxx [9, 0] xxx(7, 8)

# 也可以混合使用
s4 = "xxxx {} XXX {name} xxx {}".format(value2,value1,name="s4")
print(s4)  # xxxx [9, 0] XXX s4 xxx (7, 8)

7.3 f-string

f-string 2015 python 3.6 PEP string formatting method in accordance with the newly added 498, f-string is in fact run time calculation expression, rather than a constant value. In Python source code, f-string is a text string, the prefix is ​​'f', where the expression contained within the braces. Content curly braces expression will replace its value. E.g

import datetime
name = "zings"
age = 17
date = datetime.date(2019,7,18)
print(f'my name is {name}, this year is {date:%Y},Next year, I\'m {age+1}')  # my name is zings, this year is 2019,Next year, I'm 18

7.3.2 Format Specification Mini-Language

"Format Specification" field is used to replace the format string contained in to the respective displayed values ​​defined

The general form of standard format specifier is:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
(1) The align
align (alignment) effect
< Left (string default alignment)
> Right alignment (alignment default value)
= Forced sign between the filling and the filling numbers, numbers only filling of the support
^ Center
  • Unless the definition of the minimum field width, otherwise the field width will always be filled with the same size of its data, so in this case, an alignment option does not make sense.
  • If the align value is specified, it may be preceded by filling any character, if the default is omitted, space. Text can not use braces ( "{" or "}") as the fill character or text string format used str.format () method. However, the replacement may be inserted with nested field braces.
print(f'{name:^18}')  # |      zings     |
(2) sign

sign only digital works

sign effect
+ Enforce digital sign
- Only negative number with a leading minus sign (default)
空格 Use of a positive '' for leader, still negative '-' as the lead
print(f'{money:+}')  # +19999999877
(3) Option #

'#' Option to make "alternative forms" for conversion. For different types of alternative forms defined. This option is available only integer, float, complex and Decimal types. For integer, when using binary, octal or hexadecimal output, this option will prefix "0b", "0o" or "0x" added to the output value. For floating-point numbers, complex numbers and decimal, alternative forms can lead to conversion results always contain a decimal point character, even without the digital back as well. Typically, only if followed by a number, the results of these converted decimal point characters will appear. In addition, "g" and "G" conversion, trailing zeros are not deleted from the result.

(4), options

'' It is used to an integer part of the digital thousands separator

Descriptor effect
, Using, as the thousands separator
_ Used as the thousands separator _
  • , Only for floating point, and decimal integer complex: for floating point and a plurality of partition ,, only digits before the decimal point.
  • _ Applies to floating point, and a plurality of two, eight, ten, hexadecimal integer: for floating point and the plural, spaced _ only digits before the decimal point; for two, eight, hexadecimal integer, each secured from low to high inserting a spacer four _ (decimal integer is inserted every three _ a).
print(f'{money:,}')  # 19,999,999,877
(5) width

defined width is the minimum field width decimal integer. If not specified, the field width determined by the content.

Of course, format, there are many sturdy features, you can also look at the big brother article: Python string formatting

(6) .precision

For .precision digital object for the specified number of decimal places, if there is a decimal; for non-digital object, to specify the maximum length of the final return of the formatting characters, i.e. after formatting is complete, to the precision of the result parameter interception

(7) type

[Image dump outer link failure (img-AtydwvFj-1563463465332) (... / ... / image / python_ summarized _01.png)]

** Note: ** mini format specification language format as applicable (originally format of)

7.4 summary

The first method python format string is%, but his fatal disadvantage is the limited support type, which only supports int, str, double, all other types of conversion only for a few types, as well as If passed yuan group, you must also pass a single value tuples, do this, add the str.format () to solve some problems% -formatting in particular is that it uses an ordinary function call syntax (and therefore support multiple parameters ), and can be __format __ () method on the extension is converted into a string object. But str.format () code redundancy and there are problems, such as

v = 6*8
print("the value is {}".format(v))

The use of f-string need only

print(f'the value is{6*8}')

F readable string provides an elegant manner, Python expression can contain values ​​in the string. Including lambda expressions (to be placed in brackets)

Reference article

PEP 498

python doc

Python string formatting

F-string format string Python Overview

GitHub python face questions

Published 62 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/96466658